qadenza
qadenza

Reputation: 9293

How to find index of an image using its src attribute

<div id="store04">
<img src="g04/01.jpg" alt="img">
<img src="g04/02.jpg" alt="img">
</div>

js

$(".btnsI > img").click(function(){
var x = "g04/01.jpg";
var index = $("#store04").find(x).index();
alert (index); // -1
});

I need zero as result, because g04/01.jpg belongs to image with zero index.

Upvotes: 0

Views: 304

Answers (2)

antyrat
antyrat

Reputation: 27765

You need to use attribute equals selector for this:

$("#store04").find( 'img[src="' + x + '"]' ).index();

Upvotes: 4

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

$(".btnsI > img").click(function(){
    var x = "g04/01.jpg";
    var index = $('#store04 [src="'+ x +'"]').index();
    alert (index); // -1
});

Note I uses single quotes to allow for doubles on the [=] expression (in case the filename contains special characters, which includes the period .).

Upvotes: 3

Related Questions