How to select first parent div using jQuery?

Some time you may are in a situation need to get the text of a first div or to add an attribute to the first div in a group of divs right?

In jQuery its very simple, just look at the below example, you have a group of divs inside a div:


<div id="testdivs">
<div>This is first Div</div>
<div>other divs</div>
<div>spiderman</div>
</div>

 

And here is the code to get the text of a first div inside “testdivs”.


<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
alert($( "#testdivs div:first").text());
})
</script>
</head>
<div id="testdivs">
<div>This is first Div</div>
<div>other divs</div>
<div>spiderman</div>
</div>

Output for the above code will be:
This is first Div

The below code show how to add an attribute to the first div of a group:


<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$( "#testdivs div:first").attr('class', 'mynewclass');
})
</script>
</head>
<div id="testdivs">
<div>This is first Div</div>
<div>other divs</div>
<div>spiderman</div>
</div>

Output for the above code will be:
<div class=”mynewclass”>This is first Div</div>

I hope this will help you in a critical situation!

Add a Comment

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