RegarBoy
RegarBoy

Reputation: 3521

Change elements data by method dynamically

Below object appends div element to the body whenever obj.appendDiv() method is called.

var obj = {
    width: 100,
    height: 100,
    background: "black",
    appendDiv: function () {
        var div = document.createElement('div');
        div.style.width = this.width;
        div.style.height = this.height;
        div.style.background = this.background;
        document.body.appendChild(div)
    }
}

How to change all derived data in all appended divs whenever any parameters of obj are changed like typing obj.width = "500px" in console, changes all appended divs width.

Upvotes: 0

Views: 26

Answers (1)

guest271314
guest271314

Reputation: 1

Try creating an array div elements created by appendDiv, a method to change div elements created by appendDiv

var obj = {
    width: 100,
    height: 100,
    background: "black",
    divs: [],
    changeDivs: function(prop, val) {
      this.divs.forEach(function(el) {
        el.style[prop] = val
      })
    },
    appendDiv: function (text) {
        var div = document.createElement('div');
        div.style.width = this.width;
        div.style.height = this.height;
        div.style.background = this.background;
        div.textContent = text || "";
        this.divs.push(div);
        document.body.appendChild(div)
    }
}

obj.appendDiv("abc");
obj.appendDiv(123);
obj.changeDivs("color", "blue")

Upvotes: 1

Related Questions