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>

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments