qadenza
qadenza

Reputation: 9293

Find index of an image inside a div using a string variable

<img class="imgT" src='imgT/01.jpg' alt="img">
<div id="store">
  <img src="imgT/05.jpg" alt="img">
  <img src="imgT/01.jpg" alt="img">
  <img src="imgT/04.jpg" alt="img">
</div>

js

var x = $(".imgT").attr("src");  // imgT/01.jpg

I need to find index of that image inside #store div.

I tried this, but doesn't work:

var index = $("#store").children().find(x).index();
alert (index);  // should be 1

I got the error:
Uncaught Error: Syntax error, unrecognized expression: imgT/01.jpg

Upvotes: 0

Views: 444

Answers (2)

xaxxon
xaxxon

Reputation: 19761

Find looks in descendants, but you've already called "children" on your div. Your children don't have any descendants.

http://api.jquery.com/find/

Lose the .children call, it's not necessary.

Also, I don't believe that's a valid use of find() -- read the docs. I Don't see anything that takes a random value string and searches for that value in element attributes.

Here's what you want:

alert($("#store").find("img[src='imgT/01.jpg']").index());

This takes the #store div, calls find to search it's descendants for an img tag with the src you want. You can use text substitution to put in your 'x' variable instead of the hard coded 01.jpg string.

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20418

Try this

var x = $(".imgT").attr("src");
var index = $("#store").find('img[src="'+x+'"]').index();
alert (index)

DEMO

Upvotes: 4

Related Questions