Element.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) {
fn(i);
}
};
var li = document.getElementsByTagName('li');
li.each(function(i) {
this.style.borderBottom = '1px solid red';
});
I'm trying to make an each method like in jQuery. I tried many things in the for loop and in the callback but I got errors. I'm sure this is something to do with the 'this' context.
Yes, any code that you write in jQuery can also be written in vanilla JavaScript.
If you care about performance (and you should), using only browser-native JavaScript is the absolute fastest you can get. But, newer tools like Solid and Preact performed really close to vanilla JS.
Modern vanilla JavaScript is amazingly powerful and simple. The querySelector() and querySelectorAll() methods make getting elements in the DOM a snap.
You can use call to set context
EDIT : Element
was not the right class, it should be NodeList
and HTMLCollection
NodeList.prototype.each = HTMLCollection.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) {
fn.call(this, i);
}
};
When you use Function.prototype.call
it allows you to bind a context AKA this
to a function
There are 3 ways AFAIK to do this:
Also note that as of DOM level 4 (ES6 harmony) there is a new class called Elements
which extends Array
and is meant to replace NodeList
/HTMLCollection
, so you wouldn't need to actually extend it in ES6 to add an each
method and use Array.prototype.forEach
instead (though you won't be able to use this
in your callback.
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