Saturday, 3 October 2015

How to target specific sub element Jquery

Leave a Comment
Today i have experience difficulty to target specific sub element in my html document. So i would like to share my 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>  






By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.