jQuery :only-of-type Selector

The jQuery :only-of-type selector selects all the elements of only of matching type of its parent. If the parent element contains only the single matching and the other type element. It selects only the matching element of its parent.

jQuery :only-of-type Selector

Syntax of jQuery :only-of-type Selector

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

Syntax
$(“:only-of-type”)

It does not require any argument to pass to the selector. However, you can specify the tag name to select only the specified element.

jQuery :only-of-type Selector Select Only paragraph Type in a Div

Let us take an example of a div contains paragraph elements. There are three paragraph elements in the example given below. The selector selects the div element that contains the single matching paragraph element.

Example

Test it Live

Output

First para of first div.

Second para of first div

Third para of first div.

Span of second div.

First para of second div.

First para of third div.

The above example contains the div elements and the button. You have to click the button to get the result of the selector in the output. It applies the red color to the only element of type using the selector.

Select the List Items of the Same Type Using the Selector

Suppose you have three list elements and you have to select only the element that contain single li. Use the jQuery :only-of-type selector to select the list item that contains only of li type.

Example

Test it Live

Output

  • First item of first list.
  • Second item of first list.
  • Third item of first list.
  • First item of second list.
  • First item of third list.
  • Second item of third list.

The above example contains the button and the list elements. Click the button to highlight only the selected li element. It applies the background color as ‘yellow ‘ to the text of the selected list item.

I hope you like this tutorial of jQuery :only-of-type selector to select all elements only of type. 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