Select mutiple elements in jQuery

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

For example,


$(.class1, .class2, #id1)

In above case, select all elements that have a class name of “class1” and “class2”, and id of “id1”.

jQuery Example

In this example, the elements that have a class name of “p1” and “p2“, id of “div3” will be add a red border dynamically.


<html>
<head>
<title>Select mutiple elements example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 
</head>
<script type="text/javascript">
 
$(document).ready(function(){

	$(".p1, .p3, #div3").css("border", "2px solid red");

});

</script>
<body>

<h1>Select mutiple elements example</h1>

<p class="p1">P1</p>
<p class="p2">P2</p>
<p class="p3">P3</p>
<p class="p4">P4</p>

<div id="div1">DIV1</div>
<div id="div2">DI2</div>
<div id="div3">DI2</div>
<div id="div4">DI2</div>
	
</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Sourav Basak Recent comment authors
newest oldest most voted
Sourav Basak
Guest
Sourav Basak

For an intersection, just put the selectors together without spaces in between them. So, for an element that has an ID of a with classes b and c, you would write:

$(“#a.b.c”)

or

$(“.a”).filter(“.b”)

Get more details:

http://www.namasteui.com/select-element-with-multiple-classes/