Get class list for element with jQuery

后端 未结 17 1830
粉色の甜心
粉色の甜心 2020-11-22 03:20

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?

ex.

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 03:48

    Update:

    As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).

    const classes = element.className.split(' ').filter(Boolean);
    

    or more modern

    const classes = element.classList;
    

    Old:

    With all the given answers, you should never forget to user .trim() (or $.trim())

    Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2       class3'..

    This would turn into ['class1', 'class2','','','', 'class3']..

    When you use trim, all multiple spaces get removed..

提交回复
热议问题