I’m currently learning about the Object Literal pattern and I’m struggling with using this especially in my use case with .each().
This is what I have.
var myObject = {
el: {
divs: document.querySelectorAll(".mydiv")
},
init: function() {
this.allDivs();
},
allDivs: function() {
this.el.divs.each(this.backGround);
},
backGround: function() {
this.css("background", "red");
}
};
myObject.init();
I want to change the background to red for each div with the class .mydiv. I see that I’m using this wrong and maybe also .each() but I’m not sure what I’m looking for here and would appreciate any help.
2
Answers
If you want to use each function, you should use jquery.
Also in each function if you use ‘this’, it can’t express ‘myObject’.
It only express one element of ‘divs’.
Here is right Code.
It looks like you are trying to use the jQuery .each() function on a NodeList by document.querySelectorAll. However, .each() is a jQuery method, and you are dealing with a standard JavaScript NodeList, so you need to use a different approach to iterate over the elements.