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="https://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:
[code html]
<html>
<head>
<script src=”https://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!