jQuery – Only child selector example
Published: May 8, 2010 , Updated: May 5, 2010 , Author: mkyong
The “only-child” is used to select all elements that are the only child of their parent.
Examples
- $(‘:only-child’) – selects all elements that are the only child of their parent.
- $(‘li:only-child’) – selects all elements matched by <li> that are the only child of their parent.
jQuery Example
In this example, when the button is clicked, only the <li>DEF #1</li> will be match and change its background color dynamically, because it’s the only child of their parent.
<html> <head> <title>jQuery only child example</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> </head> <body> <h1>jQuery only child example</h1> <ul> <li>ABC #1</li> <li>ABC #2</li> <li>ABC #3</li> <li>ABC #4</li> <li>ABC #5</li> </ul> <ul> <li>DEF #1</li> </ul> <ul> <li>GHI #1</li> <li>GHI #2</li> </ul> <button>li:only-child</button> <script type="text/javascript"> $("button").click(function () { var str = $(this).text(); $("li").css("background", "white"); $(str).css("background", "coral"); }); </script> </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