jQuery :only-of-type Selector
Last Updated :
06 Jul, 2023
The :only-of-type Selector is an inbuilt selector in jQuery, used to select all the elements that are the only child of their parent.
Syntax:
$("parent_name : only-of-type")
Example 1: In this example, we are using only-of-type selectors.
HTML
<!DOCTYPE html>
< html >
< head >
< script src =
</ script >
< script >
$(document).ready(function () {
$("p:only-of-type").css(
"color", "green");
});
</ script >
</ head >
< body >
< center >
< div style = "border:1px solid;" >
< p >Geek1 of first div.</ p >
< p >Geek2 of first div.</ p >
</ div >
< br >
< div style = "border:1px solid;" >
< p >The only Geek of second div.</ p >
</ div >
< br >
< div style = "border:1px solid;" >
< span >GeeksforGeeks</ span >
< p >The only Geek of third div.</ p >
</ div >
</ center >
</ body >
</ html >
|
Output:
In the above example, all the only child element( here p tags ) of their parent( here div tags ) are formatted into green color i.e, “The only Geek of the second div.” and “The only Geek of the third div.”.
Example 2:
html
<!DOCTYPE html>
< html >
< head >
< script src =
</ script >
< script >
$(document).ready(function () {
$("p:only-of-type").css(
"color", "green");
});
</ script >
</ head >
< body >
< center >
< h3 >Division as a parent</ h3 >
< div >
< p >Geek1 of div.</ p >
< p >Geek2 of div.</ p >
</ div >
< h3 >ID as a parent.</ h3 >
< id >
< p >The only Geek of id.</ p >
</ id >
< h3 >Class as a parent.</ h3 >
< class >
< p >The only Geek of class.</ p >
</ class >
< h3 >Body as a parent.</ h3 >
< p >The only Geek of body.</ p >
</ center >
</ body >
</ html >
|
Output:
In the above example, all the only child element( here p tags ) of their respective parent are formatted into green color i.e, “The only Geek of id.”, “The only Geek of class.” and “The only Geek of the body.” as every paragraph tag is considered the different child for each parent.
Share your thoughts in the comments
Please Login to comment...