javascript - Comparing a NodeList to an Array of element id's -
i created nodelist childnodes of unordered list below
<body> <ul id="win" >win <li id="aa0">text</li> <li id="aa1"></li> <li id="aa2"></li> <li id="aa3"></li> <li id="aa4"></li> <li id="aa5"></li> </ul> </body>
and created array of element id's want compare nodelist to
['aa0','aa1,'aa7','aa8']
and used following javascript (below) compare nodelist array. objectives determine elements in array in dom or need added dom... , determine elements in dom need removed can append ul contain id's in array.
function nodeinfo(){ //these ids want in ul var ids=['aa0','aa1','aa7','aa8'] var node=document.getelementsbytagname('ul')[0]; var nodelist=node.childnodes; //test see if array ids in nodelist for(var j=0;j<ids.length;j++){ if(document.getelementbyid(ids[j])){alert(ids[j]+" here, keep")} else{alert(ids[j]+" not here, add")} } //test see if nodelist ids in array for(var j=0;j<nodelist.length;j++){ if(nodelist[j].id != undefined){ var tempi=0 for(var k=0;k<ids.length;k++){ if(nodelist[j].id === ids[k]){tempi++} } if (tempi !=1){alert(nodelist[j].id+" unwanted, remove")} } } }
currently i'm showing alerts reference appending structure. please note i'm pretty new @ this. i'm aware nodelists not behave arrays , adjusting dom in middle of function change nodelist , screw up.
my questions these: seems kind of bulky, there more concise or robust approach objective? , there inherent danger in trying adjust dom structure based on array showing here?
and please no jquery.
thanks help
instead having array of id's easier use associative array. make second loop less-cumbersome:
var ids = { aa0: true, aa1: true, aa7: true, aa8: true }; var remove = []; var add = []; for(var id in ids) if(ids.hasownproperty(id)) { if(document.getelementbyid(id) === null) { remove.push(id); } } for(var = 0; < nodelist.length; i++) { var node = nodelist[i]; if(typeof node.id !== undefined && !ids[node.id]) { remove.push(node.id); } }
the if
in second loop can changed use indexof
following if using array of id's:
if(typeof node.id !== undefined && ids.indexof(node.id) > -1) { remove.push(node.id) }
performance-wise first 1 better since lookup associative array o(1)
(unless have collision) whereas worst-case indexof
o(n)
(meaning has go through entire list find out if key exists in worst case).
Comments
Post a Comment