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>
johannchopin
  • 13,720
  • 10
  • 55
  • 101
dramasea
  • 3,370
  • 16
  • 49
  • 77
  • https://developer.mozilla.org/en-US/docs/Web/API/element.className – Phil Sep 05 '13 at 05: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. – Felix Kling Sep 05 '13 at 05:25

3 Answers3

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.

Sergio
  • 28,539
  • 11
  • 85
  • 132
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

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0
<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then:

var d = document.getElementById("div1");
d.className = d.className + " otherclass";
johannchopin
  • 13,720
  • 10
  • 55
  • 101
Sasidharan
  • 3,676
  • 3
  • 19
  • 37