12

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.

Community
  • 1
  • 1
RiceBucket
  • 169
  • 1
  • 3
  • 10

3 Answers3

32

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 */ 
}); 
Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
16

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

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Scorpion-Prince
  • 3,574
  • 3
  • 18
  • 24
3

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(){});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337