0

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.

8
  • Ehhh did you try anything? Commented Jan 25, 2016 at 5:00
  • I mean did you try to solve this somehow or do you rather not trying yourself? Commented Jan 25, 2016 at 5:03
  • To be honest I have no idea how this would be solved Commented Jan 25, 2016 at 5:10
  • And actually, I will use that way to rather larger project if I can find a solution. The code above is just a small example Commented Jan 25, 2016 at 5:11
  • If JQuery is allowed, you could use something like $("div").css("width", "500px"); Commented Jan 25, 2016 at 5:15

1 Answer 1

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")

Sign up to request clarification or add additional context in comments.

2 Comments

After change, new divs are not retrieving changed parameters. But thank you anyway, I will do the rest.
@developer Try adding properties to obj which are set if changeDivs is called, use if condition within appendDiv to check of properties of obj referencing changes are defined, if true , apply properties, values to created div within appendDiv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.