2

I have the following

CSS:

.a { position: absolute; }    
.a .b { color: red }    
.a .c { color: green }

How can i set the ".a .b" class for element with Java Script?

1
  • There is no class called .a .b. That CSS would only apply to elements with a class of b that are inside elements with a class of a. Commented Feb 20, 2015 at 11:55

1 Answer 1

5

Via className property:

var element = document.getElementById('myelement');
element.className = 'a b';

However, as mentioned by @dfsq in the comments, you probably have to fix your CSS rules to set classes for the same element rather than for its descendants, e.g. .a.b { color: red; }.

DOC: https://developer.mozilla.org/en-US/docs/Web/API/Element.className

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

2 Comments

According to OP's CSS a and b are supposed to be on different elements. Probably CSS rules are not correct.
Like this? .в, .с { position: absolute } .b { color: red } .c { color: green }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.