jQuery .first() method gets the first element in the matched elements

Syntax and Description

.first()

reduces the set of matched elements to the first in the set. Its return value is the new jQuery object.

Consider a page with a simple list as follows:


<ul>//from  w w  w.j a v a2  s. com
 <li>list item 1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 <li>5</li>
</ul>

The following code:

$('li').first().css('background-color', 'red');

marks item 1 red.

Get the first LI element

The following code gets first and last LI element.


<!DOCTYPE html>
<html>
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js">
        </script>
        <script>
            $(function(){<!--from   w w  w .  java  2s  . c  o  m-->
                var listElements = $("li");
                var firstEl = listElements.first();
                var lastEl = listElements.last();

                document.writeln("firstEl value:" + firstEl.html());
                document.writeln("firstEl length:" + firstEl.length);

                document.writeln("lastEl value:" + lastEl.html());
                document.writeln("firstEl length:" + firstEl.length);
            });
        </script>
    </head>
    <body>
        <ul>
            <li>A</li>
            <li>B</li>
            <li>java 2s.com</li>
        </ul>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities