Why class attribute cannot assign inline by javascript?

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

  • 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 .


    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


    <div id="div1" class="someclass">
        <img ... id="image1" name="image1" />
    </div>
    Then
    
    var d = document.getElementById("div1");
    d.className = d.className + " otherclass";
    
    链接地址: http://www.djcxy.com/p/25206.html

    上一篇: 让一个div标签在两个css类之间切换

    下一篇: 为什么class属性不能通过javascript内联分配?