简体   繁体   中英

How to get all the class name of an element in jquery?

I have some li's

 li class="views-row views-row-2 views-row-even"  
 li class="views-row views-row-3 views-row-odd"  
 li class="views-row views-row-4 views-row-even"  
 li class="views-row views-row-5 views-row-odd"  

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have
li class="views-row views-row-2 views-row-even selected ". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

有几种选择,但这是一个不错的选择:

views_row = $("li.selected").attr("class").match(/(views\-row\-[0-9]+)/)[0];

You haven't mentioned what's special about the view-rows-2 class:

  • Do you already know which class you want?
  • Will it always be this class?

With what information you've given, here are my suggestions:

  1. You might want to check out .hasClass()

  2. If you want all classes for an element, see Get class list for element with jQuery

So if you want to get classes based on a prefix (which in your case seems to be views-row- , you could use what's suggested in the answers to these SO question: jQuery - Get a element class based on a prefix and jQuery selector regular expressions

you can use indeOf() something like this...suppose you have that selected class as you have written..

if(class.indexOf('views-row-2')!=-1){
    //do what ever you want to do, you can use sbstr() to get your class name too.
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM