Joe
Joe

Reputation: 457

How to stop function overwriting javascript object property and add new property instead?

How can I add a new property for each element without overwriting the last property? H2 backgroundColor is overwriting H2 color in this example:

var cssObject = {}

function updateAllCSS(element, property, value) {

        cssObject[element] = [property] 
        cssObject[element][property] = value            

}

updateAllCSS('h2', 'color', '#000')
updateAllCSS('h2', 'backgroundColor', '#FFF')


console.log(cssObject.h2.color)

Any help would be amazing :)

Upvotes: 0

Views: 1224

Answers (2)

aksinghdce
aksinghdce

Reputation: 193

Use jQuery. It makes it very simple and is really very powerful in manipulation activity. In jquery it can be done like this.

Include jquery plugin library in your code using the script tag

now you can edit the properties of html elements like this:

$("#IdOfTheElement").attr("NewProperty","NewValue");

Its that simple.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382102

Create a new cssObject[element] if you don't have one.

function updateAllCSS(element, property, value) {
   if (!cssObject[element]) cssObject[element] = {};
   cssObject[element][property] = value            
}

Upvotes: 3

Related Questions