1

How can I set the CSS-class in javascript for a DIV-element?

<div id="myId">
     <!-- -->
</div>

4 Answers 4

2
document.getElementById("myId").className = "someClass";

Using jQuery:

$("#myId").attr("class", "someClass");
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the corrected post Matt. Yeah my bad my solution was not exact
1
document.getElementById("myId").className = "someClass";

Comments

0

Using JQuery

$("#myId").attr("class", "cssClass");

1 Comment

This adds to the class name; it doesn't set it as requested.
0

If you are using jQuery, use the native addClass() method, which is easier to read and purpose built for this exact question

$('#myId').addClass('foo');

2 Comments

No, as I said above, this adds a class. It doesn't set the class name.
What do you mean? The above jQuery snippet is a setter not a getter, i.e. it will add the class the the elements selected.

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.