Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple elements with jQuery

Tags:

html

jquery

ajax

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.

like image 961
RiceBucket Avatar asked Mar 28 '12 17:03

RiceBucket


People also ask

How do you select multiple elements?

Selecting multiple elements Alternatively, hold down the Ctrl / Shift key on your keyboard (Cmd key for Mac) and click the elements to select them. Tip: You can select all elements at once by pressing Ctrl+A on your keyboard.

How do you select multiple elements in JavaScript?

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.

How many types of jQuery selectors are there?

The most important functionality of jQuery is provided by it's Selectors. This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors.


1 Answers

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 */ 
}); 
like image 186
Sujit Agarwal Avatar answered Sep 22 '22 04:09

Sujit Agarwal