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


i made simple javascript adding , removing class change element background color. there button add new li elements, , no matter how many of them add works time not on last child of 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) {    (var = 0; < 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 code if condtions inside loop, checking if (e.target.parentnode.children[i].classname === '') { true atleast once, , set class current element active. time come element in loop has active class else { e.target.parentnode.children[i].classname = '';} executes , removes active class it. incase of last element never active class set again.

to fix this, in loop can set classname = '' children , later set class of current element 'active', 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 = 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>


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -