Javascript DOM How to - Check if it is the first child








Question

We would like to know how to check if it is the first child.

Answer


<!--from w  w  w.j a  va 2 s .c  o  m-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
           $("div").one('click', function () {
              if ($(this).is(":first-child")) {
                $("p").text("It's the first div.");
              }else{
                $("p").text("It's NOT the first div.");
              }
              $("p").hide().slideDown("slow");
           });
        });
    </script>
     <style>
     div { border:2px white solid;}
  </style>
  </head>
  <body>
      Press each to see the text.
      <div>asdf</div>
      <div>asdf</div>
      <div>asdf</div>
      <div>asdf</div>
      <div>asdf</div>
      <div>asdf</div>
      <p></p>
  </body>
</html>

The code above is rendered as follows: