javascript - Loop through all descendants of a div - JS only -


i've been using jquery this:

$element.find("*").each(function() {     var $this = $(this);      $this.removeattr("style width align");      if ($this.is("embed")) {         $element.append("<div class='video'></div>");         $this.attr("width", 640).attr("height", 360).parent().appendto("#" + element + " .video");     }; }); 

but i've been reading jquery's .each() method quite slow when compared simple loop (jsperf). question how can mimic pure js? find elements within div, loop through nodes.

i've tried search can seem find jquery answers - everywhere.

i've tried other things close got selecting descendants:

var children = document.getelementbyid('id').getelementsbytagname('*');  for( var = 0; i<children.lengtth; i++){     children[i].removeattribute("style");     console.log(children[i]); } 

you're doing right

var ancestor = document.getelementbyid('id'),     descendents = ancestor.getelementsbytagname('*');     // gets descendent of ancestor 

now need loop on children

var i, e, d; (i = 0; < descendents.length; ++i) {     e = descendents[i];     e.removeattribute('style');     e.removeattribute('width');     e.removeattribute('align');     if (e.tagname === 'embed') {         d = document.createelement('div');         d.setattribute('class', 'video');         ancestor.appendchild(d);     } } 

depending on you're doing, because you're using getelementsbytagname descendents, descendents live nodelist, it's length change add more nodes ancestor. if need avoid this, convert array before loop

decendents = array.prototype.slice.call(decendents); 

see this gist reusable function.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -