Create div among others instead of at the end with Javascript

Asked

Viewed 48 times

3

I managed to create the new div at the end of div id pai with .appendChild:

<div id="pai">
    <div id="filho1">texto qualquer 1</div>
    <div id="filho2">texto qualquer 2</div>
    <div id="filho3">texto qualquer 3</div>
</div>
<script>
    var nova_div = document.createElement('div');
    nova_div.innerText = 'NOVA DIV';
    document.getElementById('pai').appendChild(nova_div);
</script>

But I wanted her among the others div, instead of at the end.

Example:

<div id="pai">
    <div id="filho1">texto qualquer 1</div>
    <div id="filho2">texto qualquer 2</div>
    <div>NOVA DIV</div>
    <div id="filho3">texto qualquer 3</div>
</div>

How can I do?

  • The prepend does what you need. No link has a polyfill for IE.

  • I tried with this function, but it goes to the end as appendchild and I want to enter. But I already got with the function of Sam vlw!!

1 answer

3

You can use the .insertBefore(). It inserts a new element before a given element within a parent. Example:

var nova_div = document.createElement('div');
nova_div.innerText = 'NOVA DIV';
var pai = document.getElementById('pai');
pai.insertBefore(nova_div, pai.querySelector("#filho3"));
<div id="pai">
    <div id="filho1">texto qualquer 1</div>
    <div id="filho2">texto qualquer 2</div>
    <div id="filho3">texto qualquer 3</div>
</div>

I selected the div#filho3 with .querySelector and inserted the new div before him.

  • I knew, I did not know this function, I will use it even helped a lot!!!

  • Be sure to mark the answer with . Thanks!

Browser other questions tagged

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