How can I get <span> elements that have a specific class name in jQuery?

Using jQuery 1.9.1 and HTML5, I want to capture elements that have only specific class names.

Let's say I have the following HTML code:

<div> <span class="req">A</span> <span class="req notreq">B</span> <span class="req notreq">C</span> <span class="req">D</span> </div> 

I want to capture only <span> elements with class req , that is, the values ​​of A and D.

Using jQuery, I can capture all the values ​​using console.log($('.req')); and all notreq values ​​using console.log($('span.req.notreq'))

I need only req values. Any help?

+4
source share
3 answers

Just add the class name to the selector like this ...

 $("span[class='req']"); 

This will return span elements only with req as a class.

+8
source
 $('span.req').not('.notreq').each(function() { console.log($(this).text()); }); 
+1
source

Use: not a pseudo-element:

 $('span.req:not(.notreq)'); 
0
source

All Articles