How to keep checking for new <li> elements in a <div>?

妖精的绣舞 提交于 2020-01-16 00:43:47

问题


I want to keep checking for new li elements so that whenever there will be these new elements ,I would be getting new alerts?

JS:

$(function () {

    if ($('#div').find('<li></li>')) {
        alert('you just got new <li> elements');
    }

    // it is just an examplory function which                       
    // will keep looking for only  new <li> elements created by ol list

})(); 

Js fiddle is here http://jsfiddle.net/younis764/rWcKu/3/

Please help.


回答1:


A function like this should help you

document.addEventListener("DOMNodeInserted", function(event){
  var element = event.target;
  if (element.tagName == 'li') {
     alert("li added");    
  }
});

Check Mutation events

FIDDLE DEMO

HTML

<div id="container" style="background-color:#e0d0a0; width:300px; height:100px;"></div>   
<button onclick="AddLiToContainer ();">Add a li node to the container!</button>

JAVASCRIPT

 function AddLiToContainer() {
     var newLi = document.createElement("li");
     var textNode = document.createTextNode("Hello World");
     newLi.appendChild(textNode);
     if (newLi.addEventListener) {
         newLi.addEventListener('DOMNodeInserted', OnNodeInserted, false);
     }

     var container = document.getElementById("container");
     container.appendChild(newLi);
 }

 function OnNodeInserted(event) {
     var Li = event.target;
     alert("The text node '" + Li.innerHTML + "' has been added to an element.");
 }


来源:https://stackoverflow.com/questions/19923102/how-to-keep-checking-for-new-li-elements-in-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!