Adding HTML elements with JavaScript

Viewed 54214

So, if I have HTML like this:

<div id='div'>
  <a>Link</a>

  <span>text</span>
</div>

How can I use JavaScript to add an HTML element where that blank line is?

7 Answers

Element#after can be used to insert elements directly after a certain HTML element.

For example:

document.querySelector("#div > a").after(
  Object.assign(document.createElement('div'), {textContent: 'test', style: 'border: 1px solid'}));
<div id='div'>
  <a>Link</a>

  <span>text</span>
</div>

Related