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]); }
To loop through all DOM elements: Use the getElementsByTagName() method to get an HTMLCollection containing all DOM elements. Use a for...of loop to iterate over the collection.
jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.
If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array.
Just add position: fixed; in your div style. I have checked and Its working fine in my code. position: fixed isn't enough when you want your div to move only along with one of the scrolls, X or Y. The accepted answer is perfect.
You're already doing it right
var ancestor = document.getElementById('id'), descendents = ancestor.getElementsByTagName('*'); // gets all descendent of ancestor
Now you just need to loop over children
var i, e, d; for (i = 0; i < 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 what you're doing, because you're using getElementsByTagName
to get descendents
, descendents
is a live NodeList, so it's length will change as you add more Nodes to ancestor
. If you need to avoid this, convert it to an Array before the loop
decendents = Array.prototype.slice.call(decendents);
See this gist for a reusable function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With