Page Content

Tutorials

How to Use :Last Selector in jQuery With Code Example

:Last Selector in jQuery

A significant technique in jQuery, the :last selector is made to filter a group of matching elements and choose only the last one. In particular, it falls under the “Position among matched elements” category of filtering selectors. This feature allows developers to precisely target the last instance of a given element type or class in the Document Object Model (DOM) and conduct actions or extract data from it.

Syntax:

Using jQuery selectors is based on the basic syntax of $(selector).action(). Utilising the :last selector usually involves appending it to another selector that specifies the initial set of components that you want to filter.

$(":last")

The following are some typical syntactic variations:

  • To choose the final element of a given HTML tag type in the page, use $(‘element_type:last’). For example, $(‘p:last’) would choose the page’s final <p> element.
  • $(‘.class_name:last’) targets the last CSS-classed element. To choose the final element with the class item, use $(‘.item:last’).
  • $(‘#id_name element_type:last’): This method finds the last element_type that is a descendent of an element with a given ID, enabling more precise selection. For instance, $(‘#container div:last’).

You should be aware that all jQuery selectors, including :last, always begin with the dollar symbol and parenthesis: $().

How it Works

The :last selector’s functionality is based on jQuery’s effective handling of filtering and DOM traversal. Invoking a selector like as $(‘img:last’) causes jQuery to first find all elements that match the base selector, in this case img. As a result, a jQuery object or “matched set” with references to these DOM components is produced. Then, using the :last selection as a filter, this original collection is reduced to just the final member in that particular set.

The Sizzle selection engine that powers jQuery greatly optimises this operation. Parsing CSS selector statements and effectively collecting elements are Sizzle’s responsibilities. The usage of implicit iteration in jQuery’s selection system, which includes :last, is a major benefit. The iteration over elements to find the final one is handled internally and automatically by jQuery, in contrast to traditional JavaScript, which frequently requires the writing of explicit for loops. This implies that any methods that are chained to the target element after :last identifies it (such as.addClass() and.attr()) will work straight on that one last element without further looping code from the developer.

Web development becomes more dependable and less prone to errors because to jQuery’s unified and condensed method to accessing and modifying web page components. It also fills in the gaps of the pure DOM concept and adjusts for a number of browser-dependent peculiarities. The HTML elements of a web page are represented by the Document Object Model (DOM), a tree-like structure that jQuery efficiently traverses to make these choices.

Code Example

Here’s a real-world example of how the :last selector works: we have numerous text paragraphs and want to apply a style just to the last paragraph on the page when a button is pushed.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery :last Selector Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    .highlight-text {
      color: blue;
      font-weight: bold;
      
      padding: 5px;
      margin-bottom: 10px;
    }
  </style>
  <script>
    $(document).ready(function(){
      $("#highlightButton").click(function(){
        $("p:last").addClass("highlight-text");
      });
    });
  </script>
</head>
<body>
  <h2>Understanding jQuery :last Selector</h2>
  <p>This is the first paragraph.</p>
  <p>This is the second paragraph.</p>
  <p>This is the third paragraph.</p>
  <p>This is the fourth and final paragraph.</p>
  <button id="highlightButton">Highlight Last Paragraph</button>
</body>
</html>

Output:

Understanding jQuery :last Selector

This is the first paragraph.
This is the second paragraph.
This is the third paragraph.
This is the fourth and final paragraph.

Highlight Last Paragraph

Explanation of the Code Example

$(document).ready(function(){ … });: The enclosing JavaScript code will only run until the complete HTML document has been fully loaded and the DOM is prepared for manipulation, With this basic jQuery technique. This stops errors from happening if jQuery tries to access elements that aren’t yet displayed.

$(‘#highlightButton’).click(function() { … });: An event listener is attached to the HTML button> element with the ID highlightButton by this line. Clicking this button causes the anonymous function that was supplied as an argument to be executed, which starts the jQuery processes that follow.

var lastParagraphText = $(‘p:last’).text();:

  • (‘p:last’): This is the :last selector’s main use. The code instructs jQuery to first gather all <p> elements in the HTML text. Only the last paragraph element from this collection is selected by the :latest filter in DOM order.
  • The final paragraph is the selected element’s combined text content, which may be retrieved using the jQuery method.text(). This approach essentially ignores any HTML tags that may be present in the paragraph. Next, the text that was retrieved is saved in the lastParagraphText variable.
  • alert(…): The user is shown the text content that was extracted from the previous paragraph in an alert box.

$(‘p:last’).addClass(‘highlight-text’);:

  • The last paragraph on the page is the specific target of $(‘p:last’) once more.
  • .addClass(‘highlight-text’): This jQuery function is then used on the final paragraph that was chosen. To this element, it applies a predefined CSS class called highlight-text.
  • Applying CSS styles to highlight-text in the HTML’s <style> block changes only the final paragraph’s appearance, such as changing its colour to blue, boldness, and border.
  • This shows how jQuery may apply classes to a page to change its appearance without CSS manipulation. As previously mentioned, jQuery’s implicit iteration makes sure that this affects the targeted element without requiring additional code.

Conclusion

Developers can apply styles, change content, or take actions on a single element by using the jQuery :last selector, which is a strong and effective tool for locating the last element in a matched set. jQuery makes things simpler by abstracting away intricate DOM navigation and iteration, which would otherwise necessitate verbose JavaScript code. Developers can write code that is clearer, easier to comprehend, and less prone to errors by using :last. This is particularly helpful in dynamic interfaces where the number of items may fluctuate. All things considered, the :last selector improves client-side web development’s accuracy and versatility.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index