spyder
spyder

Reputation: 330

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

Using jQuery 1.9.1 and HTML5, I want to capture the elements which 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 the <span> elements with class req i.e. the values A and D.

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

I need only req values. Any help?

Upvotes: 4

Views: 14491

Answers (3)

Derek
Derek

Reputation: 4751

Use the :not pseudo-element:

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

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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

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

That will just return the span elements with only req as a class.

Upvotes: 10

lucuma
lucuma

Reputation: 18339

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

Upvotes: 1

Related Questions