0

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

3
  • I'd recommend against setting styles via JavaScript, and instead suggest adding/removing classes. Styles belong in stylesheets. Commented Sep 21, 2012 at 15:05
  • its to build a stylesheet for a CMS Commented Sep 21, 2012 at 15:06
  • Note that your code is flawed (apart from your question). cssObject[element] = [property] assigns an array to cssObject[element] with one element. cssObject[element][property] otoh sets the property property of that array to a certain value. You end up with an array having one element and a custom property with the same name, i.e. your array looks like {0: 'color', 'color': '#000', length: 1}. The MDN JavaScript Guide provides a good introduction to objects and arrays. Commented Sep 21, 2012 at 15:06

2 Answers 2

3

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            
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much, I can now build a CMS stylesheet with this data structure :)
0

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.

2 Comments

Setting styles without jQuery is already simple enough... recommending jQuery here does not help the OP to understand their mistake.
i'm using this to create a stylesheet

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.