RiceBucket
RiceBucket

Reputation: 169

How to select multiple elements with jQuery

I'm new to JQuery/Javascript etc... based on the following article: How to make an anchor tag refer to nothing?

I would like to apply the java function to several id's. Can we not make the function execute for classes as opposed to ids?

<span class="style1" id="myid">Link</span> 
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>
<span class="style1" id="myid">Link</span>

$('myid').click(function() { 
    /* put your code here */ 
}); 

Basically as above, how do I execute the function above for ALL of the links? Is this possible? Thanks in advance.

Upvotes: 12

Views: 41203

Answers (3)

Sujit Agarwal
Sujit Agarwal

Reputation: 12508

you should name the IDs uniquely,

<span class="style1" id="myid1">Link</span> 
<span class="style1" id="myid2">Link</span>
<span class="style1" id="myid3">Link</span>
<span class="style1" id="myid4">Link</span>
<span class="style1" id="myid5">Link</span>

then use this code

$('#myid1,#myid2,#myid3,#myid4,#myid5').click(function() { 
    /* put your code here */ 
}); 

Upvotes: 32

Scorpion-Prince
Scorpion-Prince

Reputation: 3634

Use the following

$('.style1').click(function() {      
    /* put your code here */  
}); 

This adds a click handler to all elements with class containing style1. You should not have duplicate IDs

Upvotes: 18

gen_Eric
gen_Eric

Reputation: 227240

First off, IDs should be unique. You should not have multiple elements with the same ID.

To select by ID in jQuery use the # character. $('#myid'). This will get the first element with that ID, as there should only be one (you can kinda cheat by doing $('[id="myid"]') to get get multiple elements with the same ID).

I suggest using a class to select all of your links. Classes are selected using the . character.

$('.style1').click(function(){});

Upvotes: 3

Related Questions