javascript - JS: remove lastChild only works every second button click -


i use code delete last item of <ul> list, on second, fourth, sixth, ... every second click on button item gets removed, every click message appears. can element gets deleted on every click.

document.getelementsbytagname('input')[0].onclick = function () {      'use strict';      var list = document.getelementbyid('list'), item = list.lastchild;      list.removechild(item);      window.alert("removed");  };
<ul id="list">      <li>list item 1</li>      <li>list item 2</li>      <li>list item 3</li>      <li id="child">list item 4</li>      <li>list item 5</li>  </ul>  <input type="button" value="delete last">

this because .lastchild returns nodes, including empty text nodes exist in <ul>. use .lastelementchild instead target <li> nodes

the difference between property , lastelementchild, lastchild returns last child node element node, text node or comment node (depending on one's last), while lastelementchild returns last child node element node (ignores text , comment nodes).

see html dom lastchild property , html dom lastelementchild property more information

document.getelementsbytagname('input')[0].onclick = function () {      var list = document.getelementbyid('list'), item = list.lastelementchild;      list.removechild(item);  };
<ul id="list">      <li>list item 1</li>      <li>list item 2</li>      <li>list item 3</li>      <li id="child">list item 4</li>      <li>list item 5</li>  </ul>  <input type="button" value="delete last">

some more details on why happening... when format markup clean spacing, think of "phantom" text nodes silently exist within <ul>. if minify markup following, first example indeed work fine

<ul id="list"><li>list item 1</li><li>list item 2</li><li>list item 3</li><li id="child">list item 4</li><li>list item 5</li></ul> 

plunker link - minifed markup example using .lastchild


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -