Friday, May 10, 2024
153
rated 0 times [  157] [ 4]  / answers: 1 / hits: 52076  / 11 Years ago, tue, july 23, 2013, 12:00:00

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]);
}

More From » optimization

 Answers
30

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.


[#76796] Monday, July 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;