Add class to an element

后端 未结 5 1604
遥遥无期
遥遥无期 2021-02-04 11:33

I try to write these code to make grid view through CSS:( jsbin )

   var tables = document.getElementsByClassName(\'tableData\');
    var rows = tables[0].getEle         


        
相关标签:
5条回答
  • 2021-02-04 11:43

    You might want to use a Javascript framework. It turns out that Firefox and Internet Explorer both have different approaches for adding class names.

    For Firefox, I believe you have to do

    element.setAttribute('class','<className>');
    

    while in IE, you can do

    element.className='<className>';
    

    EDIT

    It turns out that Firefox supports the element.className attribute. However, Internet Explorer doesn't understand element.setAttribute('class'...). You have to do element.setAttribute('className'...) if you want to use the setAttribute function call.

    jQuery provide an interface where you can do

    $(element).addClass('<className>');
    

    and it takes care of all the browser ambiguities. There are also removeClass() and hasClass() functions for managing and testing class attributes.

    So in your scenario, you'd do:

    var tables = document.getElementsByClassName('tableData');
    var rows = tables[0].getElementsByTagName('tr');
    for(var i=1; i<rows.length; i +=2) {
        // alert(rows[i]);
        $(rows[i]).addClass("alt");
    }
    

    Note that you could simplify this further with more jQuery functionality.

    0 讨论(0)
  • 2021-02-04 11:48

    Try rows[i].className += " alt";

    0 讨论(0)
  • 2021-02-04 11:57

    This should work even when the attribute isn't already present:

    rows[i].setAttribute("class", "alt");
    

    http://www.w3schools.com/Dom/met_element_setattribute.asp

    0 讨论(0)
  • 2021-02-04 12:00

    This will only add the class name if it doesn't already exist

    var classToAdd = 'alt';
    if (rows.className.length == 0)
    {
      rows.className = classToAdd;
    }
    else if (rows.className.indexOf(classToAdd) < 0)
    {
      rows.className += ' ' + classToAdd;
    }
    
    0 讨论(0)
  • 2021-02-04 12:04

    Two years later (2012/06), there is a new and shiny approach - element.classList with methods add(), remove(), toggle(), contains().

    rows[i].classList.add("alt");
    

    Supported by

    • Chrome 8+
    • Firefox 3.6+
    • Internet Explorer 10+
    • Opera 11.50+
    • Safari 5.1+
    0 讨论(0)
提交回复
热议问题