jQuery :only-child Selector

The jQuery :only-child selector selects all the elements that are the only child matching of its parent. If the parent contains the matching element but also contains other element types. The selector does not select the element as it requires parent that contain only that matching element.

jQuery :only-child Selector

Let it be more clear with the examples given below.

Syntax of jQuery :only-child Selector

The syntax of jQuery :only-child selector is given below.

Syntax
$(“:only-child”)

The selector requires no argument to pass to select the element. However, you have to specify the tag name when you want to select a specified element.

jQuery :only-child Selector Select If Only One Item of Table Row

Let’s takes an example of selecting the cells of a table. There are six rows in the table and the fifth row contains the single cell item. If you want to select that single-cell of a table, you have to use the selector as given in the example below.

Example

Test it Live

Output

Software Name Quantity
Microsoft Dynamics 3
Email Management Software 4
Azure 6
Above are the Management software while below is an Antivirus.
Quick Heal 11

The example uses the Colspan property of HTML in the above table. You have to click the button given in the example above. It selects the row item contains only a single td cell item. After selecting the element, if applies the background color as ‘yellow’.

Select the List Items of the Same Type Using the Selector

The list element is the group element contains many items inside. The below example contains three list elements with items. The jQuery :only-child selector select item of the list element contains only single li item. See the example below to find out.

Example

Test it Live

Output

  • Truck
  • Bike
  • Omni
  • Web Development Tutorial
  • PHP
  • jQuery

Click the above-given button to select only the child li item of their parent. It applies the ‘red’ color to the text of the selected list item. You can also apply the background color after you select the item.

I hope you like this tutorial of jQuery :only-child selector to select all elements contains an only child. If you have any queries regarding the tutorial, please comment below.

Also tell me, what other methods you are using with the selector by commenting below.

References