How to target specific sub element using Jquery

Today I have experienced difficulty to target specific sub-element in my HTML document. So I would like to share the solution that I have.

Example HTML :


  <div class="content">  
<span>element one</span>
<span>element two</span>
<span>element three</span>
<span>element four</span>
</div>

The problem is how to append text on the third sub-element under div with class content.?

Below is my solution :

   <script>  
$(document).ready(function () {
$(".content span:eq(2)").append(" <b>content three append using jquery</b><br/>");
});
</script>

From the above solution, basically telling that you can target specific sub-element using "eq(2)" --> 2 is the index with no 2. (Remember index start with 0).

Full Code Example :


  <!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="content">
<span>element one</span>
<span>element two</span>
<span>element three</span>
<span>element four</span>
</div>
<script>
$(document).ready(function () {
$(".content span:eq(0)").append(" <b>content one append using jquery</b><br/>");
$(".content span:eq(1)").append(" <b>content two append using jquery</b><br/>");
$(".content span:eq(2)").append(" <b>content three append using jquery</b><br/>");
$(".content span:eq(3)").append(" <b>content four append using jquery</b><br/>");
});
</script>
</body>
</html>

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico