JavaScript: Unable to read all elements from innerHTML content -
i trying read elements in innerhtml of div, seems alternate elements being read.
code block:
<!doctype html> <html> <body> <script type="text/javascript"> var tdiv=document.createelement("div"); tdiv.innerhtml="<span>a1</span><span>a2</span><span>a3</span><span>a4</span><span>a5</span>"; var cn=tdiv.getelementsbytagname("*"); var len=cn.length; console.log("length: "+len); console.log("tdiv len: "+tdiv.getelementsbytagname("*").length); for(var i=0;i<len;i++){ if(cn[i]){ console.log(i+": "+cn[i].nodename+": "+cn[i].tagname); document.body.appendchild(cn[i]); } } </script> </body> </html>
output: a1a3a5
note: a2 , a4 missing. have tried using both childnodes
, getelementsbytagname("*")
in browsers, ie, ff, chrome, opera, safari , see same behavior.
when add white space between spans elements being read. expected behavior ? if so, why ?
the returned item live nodelist
. appending them body
element, nodelist shrinking each iteration of for
loop. causes appear it's arbitrarily skipping elements.
try...
while (cn.length) { cn[0] && document.body.appendchild(cn[0]); }
when add white space between spans elements being read. expected behavior ? if so, why ?
yes, it's expected. means instead of skipping span
elements, it's skipping text nodes introduced spaces. never rely on - it's terribly fragile.
Comments
Post a Comment