Jquery Selectors With examples

Following are the important Jquery Selectors

Sno Selector Name Description Example Result
1 #id Select elements with id. $(document).ready(function(){
$(“#idname”).css(“background-color”,”yellow”);
});
<p id="idname">My name is Donald.</p>

My name is Donald.

I live in Duckburg.

2 .class Select all elements with class name. $(document).ready(function(){
$(“.classname”).css(“background-color”,”yellow”);
});
<p class="classname">My name is Donald.</p>

My name is Donald.

I live in Duckburg.

3 .class,.class Select multiple clases. $(document).ready(function(){
$(“.classname, .name, .end”).css(“background-color”,”yellow”);
});
<span class='classname'>My name is classname.</span><span class='name'>My name is name.</span><span class='end'>My name is end.</span>

My name is classname.

My name is name.

My name is end.

4 P Select all p elements $(document).ready(function(){
$(“p”).css(“background-color”,”yellow”);
});
<p class='classname'>My name is classname.</p><p id='name'>My name is name.</p> 
<p>My name is end.</p>

My name is classname.

My name is name.

My name is end.

5 ele1,ele2,ele3 Select multiple elements $(document).ready(function(){
$(“h2, div, span”).css(“background-color”,”yellow”);
});
<h2>Nice to meet you</h2> 
<div>Very nice indeed.</div> 
<p>I'm fine, <span>thanks.</span></p>

Nice to meet you.

Very nice indeed.

I’m fine

thanks.

6 p:first Select First element with in the p tag $(document).ready(function(){
$(“p:first”).css(“background-color”,”yellow”);
});
<p>Nice to meet you</p> 
<p>Very nice indeed.</p> 
<p>I'm fine thanks</p>

Nice to meet you.

Very nice indeed.

I’m fine thanks.

7 p:last Select Last element with in the p tag $(document).ready(function(){
$(“p:last”).css(“background-color”,”yellow”);
});
<p>Nice to meet you</p> 
<p>Very nice indeed.</p> 
<p>I'm fine thanks</p>
Nice to meet you.

Very nice indeed.

I’m fine thanks.

8 tr:even Select all even elements $(document).ready(function(){
$(“tr:even”).css(“background-color”,”yellow”);
});
<table border='1'>
<tr>
<th>Company</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
</table>
even selector selects each element with an even index number (like: 0, 2, 4, etc.).
Change background color in even numbers

Leave a Reply

Your email address will not be published. Required fields are marked *