Reputation: 2812
I'm new to jQuery. I know you can use $('.selector [attribute=value]')
to select objects in the dom but is it possible to use several atributes at once?
For example:
$('.selector [attribute=value], [attribute2=value2]')
Upvotes: 2
Views: 175
Reputation: 140042
The syntax is:
$(".selector[attribute=value][attribute2=value2]")
But if you find yourself having to create complex attribute filters, using the filter()
function might be a cleaner alternative:
$(".selector").filter(function () {
var $el = $(this);
return $el.attr("attribute") === value &&
$el.attr("attribute2") === value2;
})
Upvotes: 1
Reputation: 700232
Yes. How you do it depends on what you want to do. If you want to match either attribute you use the comma operator and complete selectors:
Like $('.selector [attribute=value], .selector [attribute2=value2]')
If you want to the elements to match both attributes, you just stack them after each other:
Like $('.selector [attribute=value][attribute2=value2]')
Note also that space is an operator, so the selector .selector [attribute=value]
matches elements with the given attribute inside an element with the class selector
, while the selector .selector[attribute=value]
matches elements both with the class selector
and the given attribute.
Upvotes: 4
Reputation: 28906
$('.selector [attribute=value][attribute2=value2]')
Source: Multiple Attribute Selector
Upvotes: 1
Reputation: 5187
it depends what you want:
selects elements with both attributes:
$('.selector[attribute=value][attribute2=value]')
selects elements with either attribute:
$('.selector[attribute=value], .selector[attribute2=value]')
Upvotes: 3
Reputation: 5865
You can use .filter() to do this.
$('li').filter("[attribute1=value1]")
.filter("[attribute2=value2]");
Upvotes: 0
Reputation: 47956
Given this HTML as a sample :
<a rel="foo">Stack Overflow</a>
<a class="bar">Server Fault</a>
This should do the trick :
$("a[rel='foo'], a[class='bar']")
Upvotes: 0
Reputation: 26380
You sure can. The selector you have suggested will select two groups, .selector [attribute=value]
and [attribute2=value2]
. If you want both, $('.selector [attribute=value][attribute2=value2]')
is the right syntax.
Upvotes: 0