简体   繁体   中英

Get Matched Class in Jquery

I have the following div in my HTML:

<div id = "foo" class = "bar barbar foobar"></div>

and I'm using this code to select the div:

$('.foo, .barfoo')

Is it possible to only get the matched class of the selected class? So for instance, if I have a barfoo class in my HTML, it would return the barfoo class, or it would return foo class if it had the foo class.

Split the selector by commas, and .find which one .matches the element you're iterating over:

 const selector = '.foo, .barfoo'; const selectors = selector.split(', '); $(selector).each(function() { console.log( selectors.find(sel => this.matches(sel)) ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id = "foo" class = "bar barbar barfoo"></div> <div class = "foo"></div>

If you want to remove the . part, .slice it off:

 const selector = '.foo, .barfoo'; const selectors = selector.split(', '); $(selector).each(function() { console.log( selectors.find(sel => this.matches(sel)).slice(1) ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id = "foo" class = "bar barbar barfoo"></div> <div class = "foo"></div>

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