jQuery's attr - return multiple classes not ju

2019-02-17 11:16发布

Given a div such as:

<div class="widget block dock clock">yada yada</div>

I'd like to be abe to use JQUERY's $(div).attr('class');

to find all the classes, but the JQUERY.attr only return widget. Is there a way with JQUERY to return all the classes defined for the element?

Thanks

4条回答
Emotional °昔
2楼-- · 2019-02-17 11:30

.attr('class') will return all classes defined for the element. Visual style is not only defined by the classes but also by css properties. You might also want to poll for them with .css('param-name')

查看更多
beautiful°
4楼-- · 2019-02-17 11:43

What you have currently will work, here's a quick demo:

alert($("div").attr("class"));​ //alerts "widget block dock clock"

Something to keep in mind is that .attr() returns that attribute on the first matched element, from the docs:

It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method.

So for example, something like this:

<div class="widget">yada yada</div>
<div class="widget block dock clock">yada yada</div>​

Would alert only "widget", since that's the class of the first matching element.

查看更多
Lonely孤独者°
5楼-- · 2019-02-17 11:46

Nick mentioned using .each()...

...but...an easier way might be to iterate via .split():

(this).attr("class").split(" ")

...then you are just dealing with a plain old javascript string array

查看更多
登录 后发表回答