[英]How do I match an element with only specific attributes and nothing else using jQuery?
Assuming example elements: 假设示例元素:
<a href="..." rel="...">...
<a href="..." rel="..." target="...">...
How can I match only the first element? 如何只匹配第一个元素? I would like to tell jQuery to match only the
<a>
element which has an href
and a rel
attribute, but no other attributes. 我想告诉jQuery仅匹配具有
href
和rel
属性的<a>
元素,而没有其他属性。 :not()
requires me to mention specific attributes to exclude, but what about unknown ones? :not()
要求我提及要排除的特定属性,但是未知属性呢?
Use filter() and check the attributes length. 使用filter()并检查属性长度。 Note that adding anything like class or data attributes would mean you would need to modify this
请注意,添加任何类似类或数据属性的内容将意味着您需要对此进行修改
$('a[href][rel]').filter(function(){ return this.attributes.length === 2; }).css('color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" rel="foo" target="_blank"> Has target</a> <a href="#" rel="foo" > No target</a> <a href="#" > No rel </a>
You can use the not() and first() function for this, to select the first element in a collection & filter out the unwanted elements. 您可以为此使用not()和first()函数,以选择集合中的第一个元素并过滤掉不需要的元素。
Example: 例:
$("a[href][rel]").not("[target]").first();
In order to exclude items that contain other unknown attributes, you should use filter as the other answers advise. 为了排除包含其他未知属性的项目,应使用其他答案建议的过滤器。
This wouldn't be a good solution however, it would be much better to add a class to the elements you need to select, or have them in another div. 但是,这不是一个好的解决方案,最好将一个类添加到需要选择的元素中,或者将它们放入另一个div中。
Use .filter()
with test condition to check element has only attributes length 使用
.filter()
和测试条件来检查元素仅具有属性长度
$('a[href][rel]').filter(function() { return this.attributes.length == 2 }).addClass('a');
.a { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="..." rel="...">...</a> <a href="..." rel="..." target="...">...</a>
You can use this.hasAttribute
and further check this.attributes.length === 2
to confirm that <a>
element has only two attributes: 您可以使用
this.hasAttribute
并进一步检查this.attributes.length === 2
来确认<a>
元素仅具有两个属性:
$('a').each(function(){ if(this.attributes.length == 2 && this.hasAttribute("href") && this.hasAttribute("rel")){ $(this).addClass('selected'); } });
.selected{ color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="..." rel="...">1111</a> <a href="..." rel="..." target="...">222</a> <a href="..." rel="...">333</a> <a href="..." rel="..." target="...">444</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.