At the parent.insertBefore(addition,target.nextSibling);
line, change the:
target.nextSibling
for only:
target
Looking like this:
parent.insertBefore(addition,target);
The value of the target
received in the function is already the element itself sent by linebreak[8]
, where linebreak
is the collection of <h2>
and [8]
is the 9th item in the collection.
In the example below I put a timer just to illustrate (just delete all commented lines):
function insertAfter(addition,target) {
var parent = target.parentNode;
if (parent.lastChild == target) {
parent.appendChild(addition);
} else {
var conta = 2; // linha exemplo
var tempo = setInterval(function(){ // linha exemplo
if(conta > 0 ){ // linha exemplo
addition.textContent = "div-content. Aguarde "+conta+" segundos"; // linha exemplo
}else{ // linha exemplo
addition.textContent = "div-content"; // linha exemplo
clearInterval(tempo); // linha exemplo
parent.insertBefore(addition,target);
} // linha exemplo
conta--; // linha exemplo
}, 1000); // linha exemplo
}
}
var adscont = document.getElementById("div-content");
var target = document.getElementById("div-target");
var linebreak = target.getElementsByTagName("h2");
if (linebreak.length > 0){
insertAfter(adscont,linebreak[8]);
}
#div-target{
background: yellow;
}
<div id="div-content">div-content. Aguarde 3 segundos</div>
<div id="div-target">
<h2>H20</h2>
<h2>H21</h2>
<h2>H22</h2>
<h2>H23</h2>
<h2>H24</h2>
<h2>H25</h2>
<h2>H26</h2>
<h2>H27</h2>
<h2>H28</h2>
<h1>H1</h1>
</div>