jQuery Selector :only-of-type

Introduction

The :only-of-type selector selects elements which is the only child of its type from its parent.

$(":only-of-type")

Select each <p> element that is the only <p> element 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-of-type").css("background-color", "yellow");
});// w w w  . ja  v a 2s .com
</script>
</head>
<body>

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

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

<div style="border:1px solid;">
  <span>This is a span element.</span>
  <p>The only paragraph.</p>
</div><br>

</body>
</html>



PreviousNext

Related