Access Multiple Elements of same ID in jQuery

If i have elements such as this

<img src='0.jpg' id='images' />
<img src='...' id='myEle' />
<img src='...' id='myEle' />

in jQuery can i do something like this

$(document).ready(function() {
    $('#myEle').mouseup(function () {

        $('#images').attr("src", myEle.getNumber() + ".jpg"); 
    }
}

Obviously each element is sorted in the correct number format that corresponds to the myEle array number


Solution 1:

Do not create markup that contains elements with duplicate IDs. This will break things, and you will be mauled by a velociraptor faster than you can say "goto".

Use classes instead:

<img src='0.jpg' id='images' />
<img src='...' class='myEle' />
<img src='...' class='myEle' />

then...

$(document).ready(function() {
    $('.myEle').live('mouseup', function () {

        $('#images').attr("src", myEle.getNumber() + ".jpg"); 
    });
});

Re: OP comment

"How do i know which image is pressed?"

Use the this keyword:

$(document).ready(function() {
    $('.myEle').live('mouseup', function () {

        $('#images').attr("src", $(this).attr('src')); 
    });
});

...I think that's what you're looking for.

velociraptor

Solution 2:

If you've inherited code so horrible that you can only work with the faulty output, use jQuery("[id=theidthatshouldbeaclassinstead]") or jQuery("[id*=theidthatshouldbeaclassinstead]") if there are multiple ids for some reason.

Solution 3:

If multiple elements will share a certain property, you should assign class to them instead of id. So the resulting jquery code will look something like:

$('.myEle').mouseup();

ID is to be used to uniquely identify elements.