jQuery – Descendant selector example
Published: May 10, 2010 , Updated: May 4, 2010 , Author: mkyong
jQuery descender selector (X Y) is used to select all elements matched by “Y” that are child, grandchild, great-grandchild, great-great-grandchild..(any levels deep) of a “X” element.
For example,
- $(‘#container div’) – selects all elements matched by <div> that are descendants of an element that has an id of container.
- $(‘form input’) – selects all elements matched by <input> that are descendants of an element matched by <form>.
jQuery Example
In this example, it used the jQuery descendant selector to add a “red border” to all the <input> fields that are descendant of a <form> element.
<html> <head> <title>jQuery descendant selector example</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <style type="text/css"> div { padding:8px 0px 8px 8px; } </style> </head> <script type="text/javascript"> $(document).ready(function(){ $("form input").css("border", "2px solid red"); }); </script> <body> <h1>jQuery child selector example</h1> <form> <label>TextBox 1 (Child) : </label><input name="textbox1"> <div class="level1"> <label>TextBox 2 (GrandChild) : </label><input name="textbox2"> </div> <div class="level1"> <div class="level2"> <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3"> </div> </div> <label>TextBox 4 (Child) : </label><input name="textbox4"> </form> <div> I'm form siblings #1 - DIV</div> <p> I'm form siblings #2 - P </p> <div> I'm form siblings #3 - DIV </div> <p> I'm form siblings #4 - P </p> </body> </html>
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at jQuery Tutorials
Actually, if my understanding is correct, the faster way to make such selections (since jquery 1.3 anyway and the Sizzle selector engine) is $(‘#container’).find(‘div’)
hi yaron, thanks for sharing your thoughts here, but may i know what causing the latter is faster?
There is a claim that Sizzler makes selections from RIGHT to left, so that $(“#somediv .someclass”) means “look in entire DOM for items with class .someclass, then for each check to see if one of it’s parents has an ID of #somediv. HOWEVER, that may be only true for anything but the id (#) selector – couldn’t find a definite answer anywhere… Should really post on it on jQuery’s own forums…