简体   繁体   中英

Adding and removing class with js works on every element of unorderd list except last child

I made simple javascript for adding and removing class to change element background color. There is a button for add new li elements, and no matter how many of them I add it works all the time but not on the last child of the list.

 var counter = 1; var newItem = document.getElementById('ulist'); var btnInput = document.getElementById('clickMe'); var headLine = document.getElementById('headline'); newItem.addEventListener('click', actItem); function actItem(e) { for (var i = 0; i < e.target.parentNode.children.length; i++) { if (e.target.parentNode.children[i].className === '') { e.target.className = 'active'; } else { e.target.parentNode.children[i].className = ''; } } } btnInput.addEventListener('click', addItem); function addItem() { newItem.innerHTML += '<li>new item' + ' ' + counter + '</li>'; counter++; } 
 .active { background-color: #FFFF80; } 
 <div class="container"> <button id="clickMe">Input Itmes</button> <ul id="ulist"> <li>First Item</li> <li>Second Item</li> <li>Third Item</li> <li>Fourt Item</li> </ul> </div> 

The problem in your code is the if condtions inside the for loop, you are checking if (e.target.parentNode.children[i].className === '') { which will be true atleast once, and then you set the class for current element as active. By the time you come to this element in the loop it already has the active class else { e.target.parentNode.children[i].className = '';} executes and removes active class from it. Incase of last element it will never get active class set again.

To fix this, in for loop you can just set className = '' for all children and then later set class of current element to 'active', something like this:

 var counter = 1; var newItem = document.getElementById('ulist'); var btnInput = document.getElementById('clickMe'); var headLine = document.getElementById('headline'); newItem.addEventListener('click', actItem); function actItem(e){ var liChildren = e.target.parentNode.children; for(var i = 0; i<liChildren.length; i++){ liChildren[i].className = ''; } e.target.className = 'active'; } 
 .active{ background-color:#FFFF80; } 
 <div class="container"> <button id="clickMe">Input Itmes</button> <ul id="ulist"> <li>First Item</li> <li>Second Item</li> <li>Third Item</li> <li>Fourt Item</li> </ul> </div> 

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