Finding the Last Element

by John H
3 minutes

Many times you want to find the last element of something. Obviously there are many different ways to find that element.

Last Element of an array: PHP

For example you can find the last element of an array with PHP using the end() function.


$fruits = array('apple', 'banana', 'cranberry'); echo end($fruits); // cranberry


The Last DOM element with JQuery

You can also find the last DOM element using JQuery. This is handy for finding things like the last <li> or the last <div>. You can find the last item in JQuery using .last()
$( "li" ).last().css( "background-color", "red" );

  • JQuery .last()
  • Traversing and Manipulating in JQuery
  • Last element in CSS

    You can use structural pseudo-classes in CSS to advance selectors allowing you to target specific elements based on their position in the document hierarchy. In the CSS you can choose the HTML element you want to add a psuedo-class to. To select the last element use ":last-child". This is a CSS3 specification so it might not work in all browsers. Here is an example. <style> li:last-child { font-weight: bold; font-size: 300% background-color: red; }</style> <ul> <li>First</li> <li>Second</li> <li>Third</li> <li>Fourth</li> <li>Fifth</li> <li>Sixth</li> <li>Seventh</li> <li>Eighth</li> <li>Ninth</li> <li>Tenth</li> </ul>

  • W3.Org CSS3 selector