:only-child Selector - Javascript jQuery Selector

Javascript examples for jQuery Selector:only-child

Description

The :only-child selector selects every element that is the only child of its parent.

The following code shows how to select each <p> element that is the only child of its parent:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p:only-child").css("background-color", "yellow");
});/*from  w w  w  .j  ava  2  s.c  o  m*/
</script>
</head>
<body>

<div style="border:1px solid;">
  <p>The first child.</p>
  <p>The last child.</p>
</div><br>

<div style="border:1px solid;">
  <p>The only child.</p>
</div><br>

<div style="border:1px solid;">
  <span>The first child.</span>
  <p>The last child.</p>
</div><br>

</body>
</html>

Related Tutorials