Let’s go through some ways to retrieve any element in a set of DOM elements in jQuery:
eq(index)
returns the element as a selector at the specified index.first()
method constructs a new jQuery object from the first element in a jQuery object that represents a set of DOM elements.last()
method constructs a new jQuery object from the last element in a jQuery object that represents a set of DOM elements.
Consider a list like this:
<ul class="sidebar-list">
<li>jQuery Plugins</li>
<li>Unity Assets</li>
<li>Android Libraries</li>
<li>>Flutter Plugins</li>
<li>Developer Tools</li>
<li>BaaS</li>
<li>WordPress Plugins</li>
<li>WordPress Themes</li>
</ul>
Get the first element
jQuery('ul li').first().text();
jQuery('ul li').eq(0).css( 'background-color', 'green' );
Get the nth element
var nthElement = jQuery('ul li').eq(n); console.log(nthElement.text())
Get the last element
jQuery('ul li').last().attr('style', 'color: red;');
jQuery('ul li').eq(jQuery('ul li').length).css( 'color', 'blue' );