ドキュメント

Core/index

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Core

index( subject )

Searches every matched element for the object and returns the index of the element, if found, starting with zero. If a jQuery object is passed, only the first element is checked.
Returns -1 if the object wasn't found.
Arguments:
subjectElement,jQuery
Object to search for.
Examples:

On click, returns the index (based zero) of that div in the page.

    $("div").click(function () {
      // this is the dom element clicked
      var index = $("div").index(this);
      $("span").text("That was div index #" + index);
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("div").click(function () {
      // this is the dom element clicked
      var index = $("div").index(this);
      $("span").text("That was div index #" + index);
    });

  });
  </script>
  <style>
  div { background:yellow; margin:5px; }
  span { color:red; }
  </style>
</head>
<body>
  <span>Click a div!</span>
  <div>First div</div>
  <div>Second div</div>
  <div>Third div</div>
</body>
</html>

Returns the index for the element with ID foobar.

$("*").index( $('#foobar')[0] )

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("*").index( $('#foobar')[0] )
  });
  </script>
  
</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>
</body>
</html>

Returns the index for the element with ID foo within another element.

$("*").index( $('#foo') )

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("*").index( $('#foo') )
  });
  </script>
  
</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>
</body>
</html>

Returns the index for the element clicked within a collection.

var mainNavLinks = $('ul#mainNav li a');
mainNavLinks.click(function(){alert(mainNavLinks.index(this));});

Returns -1, as there is no element with ID bar.

$("*").index( $('#bar')[0] )

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("*").index( $('#bar')[0] )
  });
  </script>
  
</head>
<body>
  <div id="foobar"><b></b><span id="foo"></span></div>
</body>
</html>

NameType