jQuery – Only child selector example

The “only-child” is used to select all elements that are the only child of their parent.

Examples

  1. $(‘:only-child’) – selects all elements that are the only child of their parent.
  2. $(‘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>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
newest oldest most voted