1

Code

window.onload = function() {
  var refButton = document.getElementById("old");
  refButton.onmouseover = function() {
    refButton.className = 'newClass';
  }
};
.newClass {
  color: white;
}
#old {
  color: blue;
}
<div id="old">
  Hello
</div>

If instead of ClassName I type style.color="red" then the code works.

I wonder what the problem is.

4
  • It's working, your class is applied. However, the color from the #old rule is overwriting the color, hence it stays blue. Commented May 9, 2016 at 23:21
  • 8
    CSS Specificity Commented May 9, 2016 at 23:22
  • 1
    Why is this question getting downvoted? looks like a very valid question Commented May 9, 2016 at 23:28
  • 1
    it's elementary, that's why - need to learn selector precedence. Commented May 9, 2016 at 23:41

2 Answers 2

6

It is because of CSS specificity, so just add #old to your .newClass

  • .newClass has a specificity of : 0 0 1 0
  • #old has a specificity of : 0 1 0 0

therefore #old is more specific.

using #old.newClass you get 0 1 1 0 which is going to be more specific and will apply the new style you want.

You can calculate the CSS specificity here

window.onload = function() {
  var refButton = document.getElementById("old");
  refButton.onmouseover = function() {
    refButton.className = 'newClass';
  }
};
#old.newClass {
  color: red;
  /* changed for demo */
}
#old {
  color: blue;
}
<div id="old">
  Hello
</div>

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

1 Comment

ThankYou. Is there anything else I should take care of? Stuff like this is not generally taught in tutorials.
0

if you're try to have a mouse hover effect, you can do it by replacing 'newClass' with

#old:hover{color:white;}

jsfiddle demo here

and just like adeneo's comment link said,

#old{color:blue;} //id selector

has higher priority than

.newClass{color:white;} //class selector

That's why the assignment doesn't work

Comments

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.