如何获得在jQuery中具有特定类名的元素?

时间:2023-01-22 20:34:11

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

使用jQuery 1.9.1和HTML5,我想捕获只有特定类名的元素。

Let's say I have the following HTML code:

假设我有以下HTML代码:

<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.

我只想用类req捕获元素,即值A和D。

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

使用jQuery,我可以使用console.log($('.req'))捕获所有的值;以及所有使用console.log的notreq值($('span.req.notreq'))

I need only req values. Any help?

我只需要req值。任何帮助吗?

3 个解决方案

#1


8  

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.

它只返回span元素,其中只有req作为类。

#2


1  

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

#3


0  

Use the :not pseudo-element:

使用:不是伪元素:

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

#1


8  

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.

它只返回span元素,其中只有req作为类。

#2


1  

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

#3


0  

Use the :not pseudo-element:

使用:不是伪元素:

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