Jquery select class with value

I want to use html data-* attributes and have the following images:

 <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 now can I get only those with data-selected="true" ?

I tried:

 $("img").each(function(){ if($(this)).attr("data-selected") == "true") { //do something } } 

but that doesn't seem to be the best way for me. Is there a direct selector where I can do something like

  $("img data-selected=true") ? 

thank you for your help!

+8
javascript jquery html5
source share
7 answers

$("img[data-selected='true']") , but quoting the value is optional.

PS: it's called a CSS attribute selector .

+10
source share

Well, on the one hand, you should use .data(...)

 $("img").each(function(){ if($(this)).data("selected") == "true") { //do something } } 

Or you can use:

 $("img[data-selected='true']").something... 
+7
source share

Try:

 $("img[data-selected='true']") 

Attribute equal to selector used

+5
source share

You can use attribute selector

 $("img[data-selected='true']"); 

Another alternative is filter()

 $("img").filter(function(){ return $(this).data("selected") == "true" }); 

Note that you can use the data() method to access data attributes, and you just need to pass the second half of the data attribute name.

+4
source share

Try the following selector

 $('img[data-selected="true"]') 
+3
source share

you can use

 $("img[data-selected='true']") 

there are many more selectors than just tags and classes. See here at w3.org

+3
source share

This can be done without using jQuery:

 var imgs = document.getElementsByTagName('img'); imgs.​​​​​map(function (img) { if (img.attributes["data-selected"].value == "true") { // do something } });​ 

And you do not need jQuery!

+2
source share

All Articles