Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select class with value

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!!

like image 915
Bfar221 Avatar asked Mar 14 '12 19:03

Bfar221


2 Answers

$("img[data-selected='true']") but quoting of value isn't obligatory.

PS: it is called CSS attribute selector.

like image 192
kirilloid Avatar answered Oct 13 '22 01:10

kirilloid


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...
like image 27
Naftali Avatar answered Oct 13 '22 00:10

Naftali