Reputation: 93
i want to use the html data-*
attributes and have some images like this:
<img src="http://placehold.it/100.png" data-selected="true">
<img src="http://placehold.it/100.png" data-selected="false">
<img src="http://placehold.it/100.png" data-selected="false">
<img src="http://placehold.it/100.png" data-selected="true">
<img src="http://placehold.it/100.png" data-selected="false">
how can i now just only get the ones with data-selected="true"
?
I tried:
$("img").each(function(){
if($(this)).attr("data-selected") == "true") {
//do something
}
}
but this seems not to be the best way to me. Is there a direct selector where i can do something like
$("img data-selected=true") ?
thanks for your help!!
Upvotes: 9
Views: 8302
Reputation: 2395
This is some way to do this without using jQuery:
var imgs = document.getElementsByTagName('img');
imgs.map(function (img) {
if (img.attributes["data-selected"].value == "true") {
// do something
}
});
And you don't need jQuery!
Upvotes: 2
Reputation: 3909
You can use
$("img[data-selected='true']")
there are a lot of more selectors than just tags and classes. See here on w3.org
Upvotes: 3
Reputation: 69915
You can use attribute selector
$("img[data-selected='true']");
Other alternative is filter()
$("img").filter(function(){ return $(this).data("selected") == "true" });
Note that to access data attributes you can use data()
method and you just have to pass the second half of the data attribute name.
Upvotes: 4
Reputation: 146360
Well for one thing you should use .data(...)
$("img").each(function(){
if($(this)).data("selected") == "true") {
//do something
}
}
Or you can use:
$("img[data-selected='true']").something...
Upvotes: 8
Reputation: 38137
Try :
$("img[data-selected='true']")
This uses the attribute equals selector
Upvotes: 5
Reputation: 14314
$("img[data-selected='true']")
but quoting of value isn't obligatory.
PS: it is called CSS attribute selector
.
Upvotes: 13