0

Suppose an li element of an HTML ul/li needs to be changed/edited using JS code. Basically, this is not a big task. To grab the li element, JS/CSS/JQUERY code is used, as outlined with code 1\.
And changing the textContent of the li element does the job.

The situation seems to be similar if the ul is to be extended with additional li elements. A new li can be easily inserted (code 2\), but to grap this new li fails.

code 1\
Select item from unordered list in html
http://jsfiddle.net/74g21org/1/

The HTML

<div id="items">
  <ul>
    <li jobNo="1">Item1</li>
    <li jobNo="2">Item2</li>
    <li jobNo="3">Item3</li>
  <ul>
</div>

And the jquery to grap the li element, remember job/li details

let jobNo;
let jobText;

$("#items ul li").click(function(){
    $("#items ul li").css("color","inherit");
    $(this).css("color","green");  
    jobNo = this.getAttribute('jobNo');
    jobText = this.textContent;
});

Changing the li textContent

items.childNodes[+jobNo+1].textContent = new_textContent;

code 2\
Add/insert a new li element

  let newtext = document.createTextNode("new...Content");
  let newElem = document.createElement("li");
  newElem.setAttribute('jobNo', jobNo);
  newElem.appendChild(newtext);
  let list = document.getElementById("items");
  list.insertBefore(newElem, list.childNodes[+jobNo+1]);
  //list.replaceChild(newElem, list.childNodes[+jobNo+1]);

Problem why don't listen lielements inserted or replaced with code 2\ ?
It seems jquery gets an initial snapshot and afterwards new/added/replaced elements are excluded.
Or how to make sure they are included?

neandr
  • 199
  • 1
  • 2
  • 13

0 Answers0