Add class to an element

后端 未结 5 1614
遥遥无期
遥遥无期 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','');
    

    while in IE, you can do

    element.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('');
    

    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

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

提交回复
热议问题