DEV Community 👩‍💻👨‍💻


Posted on

Add to the DOM with JavaScript

I hate adding elements to the DOM using JavaScript. This is because it's really easy with jQuery, something I have to look up every time in JavaScript, and really easy in React. I pretty much learnt React to avoid doing it in JavaScript.

But I thought I'd post about it because then maybe I'll get it into my head. And if I don't, then I'll have this post to look it up on.


This appends to the end of the element. So this is how to add a paragraph to the end of a div with a class of .section.

  const newElement = document.createElement('p');
  const newContent = document.createTextNode('This is a paragraph');
Enter fullscreen mode Exit fullscreen mode

What each line here is doing:

  1. Telling it we want to create a p element - giving it a name here means we can refer to it later by newElement. No need to pick it up using its class
  2. Adding some content to the element - in this case it's some text
  3. Adding the text to the element
  4. Adding a class to the element so it can be referred to when styling
  5. Adding this new element to the end of .section


This inserts the element before another element.

  const newElement2 = document.createElement('p');
  const newContent2 = document.createTextNode('This is another paragraph');
  document.querySelector('.section').insertBefore(newElement2, newElement);
Enter fullscreen mode Exit fullscreen mode

The main difference here is the last line. You give it the parent element, then in insertBefore the first bit is your new element to be inserted, then you tell it what to insert it before.

I find appendChild to be more intuitive than insertBefore.

Top comments (1)

ultimatepryme profile image

Great job mate

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.