Change Javascript code to display div before H2

Asked

Viewed 54 times

0

How to change this javascript code to display div-Content before H2, instead of after, as it is currently?

<script type='text/javascript'>
function insertAfter(addition,target) {
    var parent = target.parentNode;
    if (parent.lastChild == target) {
        parent.appendChild(addition); 
    } else {
        parent.insertBefore(addition,target.nextSibling);
    }
}
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]);
}
</script>

1 answer

0

On the line parent.insertBefore(addition,target.nextSibling);, swap the:

target.nextSibling

by just:

target

Thus remaining:

parent.insertBefore(addition,target);

The value of 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>

Browser other questions tagged

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