I've been using jQuery to do 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 that jQuery's .each()
method is quite slow when compared to a simple for loop (jsPerf). My question is how can I mimic this with pure JS? Find all elements within a div
, then loop through the nodes.
I've tried to search for this but all I can seem to find are jQuery answers - everywhere.
I've tried other things but this was as close as I got to selecting all descendants:
var children = document.getElementById('id').getElementsByTagName('*');
for( var i = 0; i<children.lengtth; i++){
children[i].removeAttribute("style");
console.log(children[i]);
}
could you just use something as simple as this?
I commented in @Paul S.'s answer that you could can also clone the node and use a document fragment to add new embeds. Here is an example:
HTML:
JS:
You can see the demo here.
Cloning the node prevents the live modification of the DOM since the style attribute can have properties that cause the browser to repaint numerous times.
You can use querySelectorAll's forEach function.
You're already doing it right
Now you just need to loop over
children
Depending on what you're doing, because you're using
getElementsByTagName
to getdescendents
,descendents
is a live NodeList, so it's length will change as you add more Nodes toancestor
. If you need to avoid this, convert it to an Array before the loopSee this gist for a reusable function.