Friday, December 5, 2014

Tutorial for Selecting nth last element using jquery || using nth-last-child in jquery

hi let see how to select a nth last element like the <div>, <p>, <h1> etc. using jquery.
Now in below example just to check if we have selected the correct element we will change its color
example for selecting a 2nd last <h1> element which is inside a <div>
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title></title>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“button”).click(function () {
$(“h1:nth-last-child(2)”).css(“background-color”, “yellow”);
});
});
</script>
</head>
<body>
<div>
<h1>im 1st h1</h1>
<h1>im 2nd h1</h1>
<h1>im 3rd h1</h1>
<h1>im 4th h1</h1>
<h1>im 5th h1</h1>
</div>
<button>Change color of 4th element ( as it is 2nd last )</button>
</body>
</html>

output:
1

No comments:

Post a Comment