DEV Community

Jasterix
Jasterix

Posted on • Updated on

3 JavaScript Snippets to get you started

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)
})
Enter fullscreen mode Exit fullscreen mode

Add API objects to DOM

const render=(book)=>{
return(`<div>
    <h1>${book.title}</h1>
    <button class='del-btn> 🗑</button>
`)}
Enter fullscreen mode Exit fullscreen mode

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()
      }
  }
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.