Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to make an each method, like in jQuery, with vanilla JS

Tags:

javascript

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.

like image 490
Victor Rico Avatar asked Dec 18 '14 10:12

Victor Rico


People also ask

Can you mix jQuery and vanilla JS?

Yes, any code that you write in jQuery can also be written in vanilla JavaScript.

Is vanilla JavaScript better?

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.

Is vanilla JavaScript hard to learn?

Modern vanilla JavaScript is amazingly powerful and simple. The querySelector() and querySelectorAll() methods make getting elements in the DOM a snap.


1 Answers

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:

  • call (as said above)
  • apply (which works like call except it takes only two arguments, the second being an array)
  • bind (which is used for currying)

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.

like image 75
axelduch Avatar answered Sep 23 '22 10:09

axelduch