Add child element before other

Asked

Viewed 440 times

1

I’ll explain:

Assuming I have the following code:

const filho = document.createElement('li')
const text = document.createTextNode('Filho 0')

filho.appendChild(text)
document.getElementById('ul-pai').appendChild(filho)
<ul id="ul-pai">
    <li>Filho 1</li>
    <li>Filho 2</li>
</ul>

As you can see, he inserts son 0 after son 2.

Assuming I want to insert the same before child 1, that is, at position 0 of the array, this would be possible?

1 answer

1


You can use the method insertAdjacentElement:

const filho = document.createElement('li')
const text = document.createTextNode('Filho 0')

filho.appendChild(text)

document.getElementById('ul-pai').insertAdjacentElement('afterbegin', filho)
<ul id="ul-pai">
    <li>Filho 1</li>
    <li>Filho 2</li>
</ul>

The parameters for insertAdjacentElement may be:

  • beforebegin: before the informed element.
  • afterbegin: inside the element, at the beginning before the first child.
  • beforeend: inside the element, after the last child.
  • afterend: after the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.