13
<html>
  <head>
    <style>     
      .tagging {
        border: 1px solid black;
        width: 20px;
        height: 30px;
      }
    </style>
    <script>
      window.onload = function() {
        var div = document.getElementsByTagName("div");
        div[0].class = "tagging";
      }     
    </script>
  </head>
  <body>
    <div></div>
  </body>
</html>

This is my code. I wonder why it doesn't work when I assign class attribute via javascript, but it works when I assign inline directly in html

<div class="tagging"></div>
2
  • developer.mozilla.org/en-US/docs/Web/API/element.className Commented Sep 5, 2013 at 5:17
  • 2
    Sine class is a reserved keyword in many languages, the creators of the DOM API decided to map the class attribute to the className property. In JavaScript it wouldn't actually matter because even though class is a reserved keyword, you can use such keywords as property names. Commented Sep 5, 2013 at 5:25

3 Answers 3

11

You need to use className.

Try:

div[0].className = "tagging";

If you want to add tha class to the existing one you can use:

div[0].className += " tagging"; // adding white-space is important

Demo here

To read: MDN className.

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

Comments

4

use className, so change:

var div = document.getElementsByTagName("div");
div[0].class = "tagging";

to

var div = document.getElementsByTagName("div");
div[0].className = "tagging";

Demo:: jsFiddle

Comments

0
<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then:

var d = document.getElementById("div1");
d.className = d.className + " otherclass";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.