aalaap
aalaap

Reputation: 4401

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. :not() requires me to mention specific attributes to exclude, but what about unknown ones?

Upvotes: 1

Views: 82

Answers (4)

charlietfl
charlietfl

Reputation: 171669

Use filter() and check the attributes length. 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>

Upvotes: 4

totallyNotLizards
totallyNotLizards

Reputation: 8569

You can use the not() and first() function for this, to select the first element in a collection & filter out the unwanted elements.

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.

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can use this.hasAttribute and further check this.attributes.length === 2 to confirm that <a> element has only two attributes:

$('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>

Upvotes: 0

Satpal
Satpal

Reputation: 133403

Use .filter() with test condition to check element has only attributes length

$('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>

Upvotes: 0

Related Questions