• Home
  • About me

DotNetSwede

A blog about .NET, C#, JavaScript and technology in general.

jQuery

Selecting the First or Last Element using jQuery

6th February 2016 by Jonathan Lindkvist Leave a Comment

It’s very common that you might want to target the last and/or the first element matching a particular query selector (e.g. <li> elements). As you can see from the snippets below, jQuery makes such tasks quite easy.

A list of elements…

For the jQuery samples below, just assume we’re targeting an unordered list like the one below:

<ul>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>

Selecting the first list element using jQuery

var firstListItem = $('li').first();

Selecting the last list element using jQuery

var lastListItem = $('li').last();

Setting a different styling for the first element

If your intention is to change the styling for the first or last element, then all you have to do is to add another method (through a concept called method chaining) like this:

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

 

For more information, make sure to check out the jQuery documentation for the first() and last() methods.

Posted in: jQuery Tagged: first(), jQuery, last(), Traversing

Recent Posts

  • Clean Architecture
  • AngularJS to Angular Upgrade Paths
  • Web Scraping with C#
  • ASP.NET Core MVC Anatomy
  • Migrating to TypeScript

Recent Comments

  • Sam on Brace Completion and Auto Indentation in VS
  • lily on C++ for C# Developers
  • Tushar Soni on Building a Blog Using ASP.NET Core
  • Tushar Soni on Building a Blog Using ASP.NET Core
  • bob on Terminals and Command Prompts

Archives

  • January 2018
  • August 2017
  • July 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • January 2016

Categories

  • .NET
  • .NET News
  • ASP.NET
  • Content Management Systems (CMS)
  • Fun
  • JavaScript
  • jQuery
  • Learning
  • Tools
  • Visual Studio
  • Webdesign

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright © 2018 DotNetSwede.

Omega WordPress Theme by ThemeHall.