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>
4

3 回答 3

11

你需要使用className.

尝试:

div[0].className = "tagging";

如果您想将 tha 类添加到现有的类中,您可以使用:

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

演示在这里

阅读: MDN类名

于 2013-09-05T05:18:06.093 回答
4

使用className,所以改变:

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

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

演示:: jsFiddle

于 2013-09-05T05:17:55.450 回答
0
<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

然后:

var d = document.getElementById("div1");
d.className = d.className + " otherclass";
于 2013-09-05T05:19:26.117 回答