Chaitanya Lakshmi
  • About Me
  • Job Duties
  • Knowledge Blog
  • Applications
  • Contact Us
    • Linked In
    • Facebook
  • About Me
  • Job Duties
  • Knowledge Blog
  • Applications
  • Contact Us
    • Linked In
    • Facebook

jQuery parent() vs. parents()

2/27/2012

0 Comments

 
Given the following HTML:

<html>…<body><div ”one”><div ”two”><p><span>Some text</span></p></div></div></body></html>

$(‘span’).parent() will select the <p> tag such that the element set in the jQuery object is [span].

$(‘span’).parents() will select all parent tags such that the element set in the jQuery object is [p, div.two, div.one, body, html].

So parent() will select the first parent element while parents() will select all elements straight up the DOM tree.

Now jQuery has some great flexibility in that you could do that following:

$(‘span’).parents().filter(‘div’) which would result in [div.two, div.one]. jQuery makes it even easier as the parent() and parents() methods support filtering built in so the above can be reduced to:

$(‘span’).parents(‘div’) giving you [div.two, div.one].

Let’s continue with one more example, let’s say that you only need the first div in the parent DOM tree, jQuery to the rescue $(‘span’).parents(‘div:eq(0)’) will give you [div.two]

0 Comments



Leave a Reply.

    Archives

    April 2012
    March 2012
    February 2012

    Categor

    All
    Ajax
    Api
    Cross Site Scripting
    Css
    Curl
    Design Patterns
    Drupal
    Exception Handling
    Htaccess
    Html
    Javascript
    Jquery
    Json
    Linux
    Mysql
    Oops
    Php
    Regular Expressions
    Web 2.0
    Webservices
    Wordpress
    Xhtml

    RSS Feed

Powered by Create your own unique website with customizable templates.