loading...

3 JavaScript Snippets to get you started

jasterix profile image Jasterix Updated on ・1 min read

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

Discussion

pic
Editor guide
Collapse
rajnishkatharotiya profile image
Info Comment marked as low quality/non-constructive by the community. View code of conduct
Rajnish Katharotiya

Really amazing article on JS Snippets, I have also started a series for the same.
Check snippet for how to validate every record of the collection with a unique case on youtu.be/p5JW6YIh5yo

"" Thanks for watching, if you found it informative - please subscribe the channel to support me. ""