skip to Main Content

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


  1. 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.

         var myObject = {
    
            el: {
                divs: $(".mydiv")
            },
    
            init: function() {
                this.allDivs();
            },
            
            allDivs: function() {
                this.el.divs.each(function() { myObject.backGround($(this)) });
            },
                
            backGround: function(div) {
                div.css("background", "red");
            }
        };
    
        myObject.init();
    
    Login or Signup to reply.
  2. 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.

    const myObject = {
        el: {
            divs: document.querySelectorAll(".mydiv")
        },
    
        init() {
            this.allDivs();
        },
    
        allDivs() {
            this.el.divs.forEach(div => this.backGround(div));
        },
    
        backGround(div) {
            div.style.background = "red";
        }
    };
    
    myObject.init();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search