:first-of-type Selector - Javascript jQuery Selector

Javascript examples for jQuery Selector:first-of-type

Description

The :first-of-type selector selects elements who are the first child by a particular type inside their parent.

The following code shows how to select every <p> element that is the first <p> element 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(){
    $("button").click(function(){
        var btn = $(this).text();
        $("p").css("background-color", "white");
        $("p" + btn).css("background-color", "yellow");
    });/*from ww w  .  j  a v  a2 s  .c  om*/
});
</script>
</head>
<body>

<p>A</p>

<div style="border:1px solid;">
  <p>B</p>
  <p>C</p>
</div><br>

<div style="border:1px solid;">
  <span>D</span>
  <p>E</p>
  <p>F</p>
  <span>G</span>
</div><br>

<div style="border:1px solid">
  <p>H</p>
  <p>I</p>

    <div style="border:1px solid">
      <p>X</p>
      <p>Y</p>

      <div style="border:1px solid">
          <p>X</p>
          <p>Q</p>
      </div>

    </div>

</div>

<p>The last paragraph in body, and the last child in div.</p>

<button>:first</button>
<button>:first-child</button>
<button>:first-of-type</button><br><br>

</body>
</html>

Related Tutorials