tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

first()

Returns: jQuery

Description: Reduce the set of matched elements to the first in the set.

.first()

version added: 1.4

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first matching element.

Consider a page with a simple list on it:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>
We can apply this method to the set of list items:
$('li').first().css('background-color', 'red');
The result of this call is a red background for the first item.
  • list item 1
  • list item 2
  • list item 3
  • list item 4
  • list item 5

Example

Highlight the first span in a paragraph.
$("p span").first().addClass('highlight');
The output of the code above will be:

Full source

Highlight the first span in a paragraph.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <style>.highlight{background-color: yellow}</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script type="text/javascript" language="javascript">
   $(document).ready(function(){
     $("p span").first().addClass('highlight');
   });
  </script>
</head>
<body>
<p><span>Look:</span> <span>This is some text in a paragraph.</span> <span>This is a note about it.</span></p>
</body>
</html>
Was this information helpful?
   

Comments