Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Multiple Elements of same ID in jQuery

Tags:

html

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

like image 276
Angel.King.47 Avatar asked Jan 25 '11 04:01

Angel.King.47


People also ask

Can I have multiple elements with same ID?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

How do I select all elements with the same ID?

In simple way if you use id to select all div having same ids then it will select first id only but if you want to select ,want go through each div or any other element with same id then I will explain you how you can do that. $( '#red' ). css( 'background-color' , 'red' ); $( '#green' ).

Can I select multiple ID in JQuery?

Given an HTML document and the task is to select the elements with different ID's at the same time using JQuery. Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element.

How can I get multiple elements ID?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements. Here is the HTML for the examples in this article.


2 Answers

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

like image 153
Matt Ball Avatar answered Sep 24 '22 07:09

Matt Ball


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.

like image 30
Cees Timmerman Avatar answered Sep 22 '22 07:09

Cees Timmerman