Tom
Tom

Reputation: 950

Javascript: Change css child nodes in id

Perhaps the answer is relatively simple, but I just started with Javascript and I can't seem to achieve my goal:

I've got this piece of CSS code:

#tabmenu li a {
background: #ACBACF;
}

Now I want to change the background, but not only for #tabmenu, li or a, but all of them. How do I do this with Javascript?

Edit: This is a button with a background, I want to know how to change the values of the css part. So it's not only background, but also padding and stuff, but to make it simple, let's say I just want to change the background with javascript.

HTML:

<ul id="tabmenu">
       <li>
           <a href="#index">Home</a>
      </li>
</ul>

Edit 2: I can't change the HTML or the CSS, because I want to create a userscript (Greasemonkey).

Upvotes: 0

Views: 426

Answers (1)

sixFingers
sixFingers

Reputation: 1295

I don't think setting css directly from Javascript is the best approach. It leads to a lot of inline code and doesn't play very well with the style you defined in an external file. If your going for heavy modification of css, I suggest injecting a custom style tag inside the dom:

var style = document.createElement("style")
style.setAttribute("type", "text/css");
style.innerHTML = "#tabmenu li a {\
    background: red;\
}";
document.getElementsByTagName("head")[0].appendChild(style)

The "\" at the end of lines are needed in Javascript when using multiline string values.

In the end, if you follow this route, i would suggest writing the css code in a text editor, then pack it with something like https://csscompressor.net/ (this will give you a single-line string) and copy-paste the result between the brackets.

Upvotes: 2

Related Questions