3 JavaScript Snippets to get you started
Jasterix
Posted on July 3, 2019
After a bitter battle with React, I jumped at the chance to answer some questions questions I got about JavaScript. While those conversations took place offline, I still think it might be helpful to provide some snippets for the most common problems other programming students were struggling with.
Manipulating the DOM
- In JavaScript, this happens over 3 parts:
- Fetch requests or API calls
- Rendering on the DOM
- Event Handling
More and more, I understand why most programming blog posts tend to be on the longer side. But as always, I will try to provide some (templated) short snippets, with little commentary, followed by a third-party resource which goes into more detail.
Fetch requests (GET)
let url = "http://localhost:3000/books"
fetch(url)
.then(res => res.json())
.then(data=> {
data.forEach(book => {
parentElement.innerHTML += render(book)
})
Add API objects to DOM
const render=(book)=>{
return(`<div>
<h1>${book.title}</h1>
<button class='del-btn> 🗑</button>
`)}
Add event handler to delete item from DOM on click
let divTag = document.querySelector('div')
divTag.addEventListener('click', (event) => {
if(event.target.className.contains('del-btn') {
event.target.parentElement.remove()
}
}
These are extremely simplified examples to give you an idea of how these 3 parts can interact with each other. For more detailed reading, this article by freecodecamp provides a great basis exploring JavaScript DOM manipulation and API calls in more detail
Posted on July 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.