checks for the existence of a value in the array

Description

.inArray() checks for the existence of a value in the array and returns the index of the value if found. If the value isn't in the array, -1 is returned.

Example


<!DOCTYPE html>
<html>
  <head>
  </head><!--   w  w  w  .  ja  v  a 2 s .  c o  m-->
  <body>
    <p></p>
    <p></p>
    <p></p>
    <p class="duplicate"></p>
    <p class="duplicate"></p>
    <p class="duplicate"></p>
    <p></p>  
    <script 
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
    </script>
    <script>     
      $(document).ready(function(){
          // select all paragraph elements
          var paragraphs = $( "p" ); 
          
          //returns 7
          console.log( paragraphs.length );
       
          //turn it into an array
 
          paragraphs = $.makeArray( paragraphs );
          
          //get elements of class duplicate and immediately convert them to an array
          var dupes = $.makeArray($( ".duplicate" ))
 
          //concat them into our paragraphs array 
          paragraphs = paragraphs.concat( dupes );
          
          //returns 10
          console.log( paragraphs.length );
          
          //get rid of the dupes
          paragraphs = $.unique( paragraphs );
          
          //returns 7
          console.log( paragraphs.length );
          
          var index = $.inArray("6", paragraphs);
          console.log(index); // returns -1
      });
    </script>
 
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities