$('p').text('Hello.')
over for (var p in document.getElementsByTagName('p')) { p.innerHTML = 'Hello.'; }
any day!The proper way is:
for( var i=0, ps=document.getElementsByTagName('p'), len=ps.length; i < len; i++) {ps[i].innerHTML = 'Hello.';}
Edit: I think I missed what you said. You're saying it's "like" and array, but unlike arrays its `length` is enumerable. I'll leave my comment so other skeptics can benefit :)
Edit2: This is what I was referring to (read the 'Note' at the right side): http://bonsaiden.github.com/JavaScript-Garden/#object.forinl...
paras = document.getElementsByTagName('p') for (var para in paras) { console.log(para)} 0 1 ... 9 10 length item
var paragraphs = document.getElementsByTagName('p');
paragraphs.forEach(function(paragraph){paragraph.innerHTML = 'Hello.';})
document.getElementsByTagName returns a DOM Node List and it does not have forEach method according to the DOM spec. DOm Nodes, Elements and Node Lists and Node Maps do not follow the javascript spec (ECMAScript) hence do not share methdos and properties. A Dom Node List does not have the methods of the javascript array. That is because DOM Node List does not inherit from the Array.prototype, because it is not javascript - it has its own spec that exactly determines what methods and properties it should have. The implementation in the browser happens to be accessible through javascript but that does not mean that the DOM is part of javascript. That is why wrapper libraries like jQuery or other abstractions are necessary to make the DOM much more accessible from a JS perspective. BTW that is why many people confuse DOM with javascript and then get frustrated which is understandable.
for (var p in document.getElementsByTagName('p')) {console.log(p);}
This discussion is a bit like how assembly programmers used to defend not moving to a high level language long after the performance benefits were not worth it any more.
Such as?
Yes, but it's also more probable that it won't go on at all (due to browser incompatibilities and such).
ps. second example is not valid, in Vanilla JS you do it like this:
document.getElementsByTagName('p').filter(function(el) {
el.innerHTML = 'Hello.';
});Array.prototype.forEach.call(document.getElementsByTagName('p'), function(el) { el.innerHTML = 'Hello.'; });
TypeError: document.getElementsByTagName("p").filter is not a function
Because you don't get an array, only something array-like.
Erm... no you don't: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082