jQuery Selector :only-child

Introduction

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

$(":only-child")

Select each <p> element that is the only child of its parent:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:only-child").css("background-color", "yellow");
});/* ww  w.j  a  v  a  2  s  . co  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>



PreviousNext

Related