0

I'm trying to discover the best way of inserting an element (in this case, #test) after a specific element to become its sibling. Take the example below:

The HTML:

<div id='parent'>
  <div class='child' id='one'>
    child 1
  </div>
  <div class='child' id='two'>
    child 2
  </div>
  <div class='child' id='three'>
    child 3
  </div>
  <div class='child' id='four'>
    child 4
  </div>
  <div class='child' id='five'>
    child 5
  </div>
</div>

<div id='test'>test</div>

The Javascript:

const test = document.getElementById('test');

test.parentNode.appendChild(test);
// how to insert #test after #four and before #five

I want to be able to insert the test div between the siblings with ids four and five. The javascript I've written fails. Can anyone think of the best way of doing this?

Thanks for any help here - you can find a codepen URL below:

Codepen URL: https://codepen.io/ns91/pen/XWWdjXx

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • [MDN insertAdjacentElement](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement) is also an option. – Taplar Oct 14 '19 at 15:59

2 Answers2

1
const test = document.getElementById('test');
const five = document.getElementById('five');

five.parentNode.insertBefore(test, five);
SergeyA
  • 4,427
  • 1
  • 22
  • 15
1

You can use insertBefore

let tst = document.getElementById('test');
var fifthChild = document.getElementById('five');
document.getElementById('parent').insertBefore(tst, fifthChild);
<div id='parent'>
  <div class='child' id='one'>
    child 1
  </div>
  <div class='child' id='two'>
    child 2
  </div>
  <div class='child' id='three'>
    child 3
  </div>
  <div class='child' id='four'>
    child 4
  </div>
  <div class='child' id='five'>
    child 5
  </div>
</div>

<div id='test'>test</div>
brk
  • 48,835
  • 10
  • 56
  • 78