Nic
This week I learnt...

This week I learnt...

Add to the DOM with JavaScript

Nic's photo
Nic
·Jul 17, 2022·

2 min read

Play this article

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.

appendChild

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');
  newElement.appendChild(newContent);
  newElement.classList.add('paragraph');
  document.querySelector('.section').appendChild(newElement);

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

insertBefore

This inserts the element before another element.

  const newElement2 = document.createElement('p');
  const newContent2 = document.createTextNode('This is another paragraph');
  newElement2.appendChild(newContent2);
  newElement2.classList.add('paragraph2');
  document.querySelector('.section').insertBefore(newElement2, newElement);

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.

 
Share this