简体   繁体   中英

Button works only after second click

Close button which remove the elements from DOM, work only on the second click.

Here is HTML part of button: That is closeBtn.

 function removeHeader() { var list = document.getElementById("main"); list.removeChild(list.childNodes[0]); } 
 <div id="main"> <div class="nanoSaturnBanner"> <p>teteasdasdasdsadasds sad asdasdasdasdasdas</p> <div class="banner-buttons"> <label class="showme">Ads by Google</label> <a class="infoLink" href="https://support.google.com/adsense/#topic=3373519" target="_blank"> <i class="fas fa-info-circle"></i> </a> <div class="closeBtn" onclick="removeHeader()"> closeBtn </div> </div> </div> </div> 

You should use list.childNodes[1] because the list.childNodes[0] represent the #text node that is the whitespaces after <div id="main"> . So, in first click it was removing that node and in second click it was removing the actual node with <div class="nanoSaturnBanner">

 function removeHeader() { var list = document.getElementById("main"); list.removeChild(list.childNodes[1]); } 
 <div id="main"> <div class="nanoSaturnBanner"> <p>teteasdasdasdsadasds sad asdasdasdasdasdas</p> <div class="banner-buttons"> <label class="showme">Ads by Google</label> <a class="infoLink" href="https://support.google.com/adsense/#topic=3373519" target="_blank"> <i class="fas fa-info-circle"></i> </a> <div class="closeBtn" onclick="removeHeader()"> <i class="far fa-window-close">close</i> </div> </div> </div> 

Note : Whitespace inside elements is considered as text, and text is considered as nodes. Comments are also considered as nodes.

As childNodes get none element nodes as well, like text and comment , use eg children instead to get the first actual element.

Note, with that you also make sure getting the element no matter how many "none element nodes" their might be in your markup.

Stack snippet

 function removeHeader() { var list = document.getElementById("main"); list.removeChild(list.children[0]); } 
 <div id="main"> <div class="nanoSaturnBanner"> <p>teteasdasdasdsadasds sad asdasdasdasdasdas</p> <div class="banner-buttons"> <label class="showme">Ads by Google</label> <a class="infoLink" href="https://support.google.com/adsense/#topic=3373519" target="_blank"> <i class="fas fa-info-circle"></i> </a> <div class="closeBtn" onclick="removeHeader()"> <i class="far fa-window-close">close</i> </div> </div> </div> 

function removeHeader() {
   var list = document.getElementById("main");
   list.remove(list.childNodes[0]);  // replacing removeChild with remove worked
}

Check the fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM