
jQuery :lt() selector
The jQuery :lt()
selector is used to select all elements at an index less than the specified index within a matched set of elements. It allows you to filter elements based on their position in the selection.
Here’s the basic syntax of the :lt()
selector:
$(selector:lt(index))
Parameters:
selector
: A selector expression used to select the elements you want to filter.index
: An integer value representing the maximum index for the selection. Elements at an index less than this value will be included in the result.
Return Value:
The :lt()
selector returns a jQuery object containing the elements that match the condition based on their index.
Example:
<!DOCTYPE html>
<html>
<head>
<title>jQuery :lt() Selector Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<script>
$(document).ready(function() {
// Select the first two li elements (index 0 and 1)
var selectedItems = $("li:lt(2)");
// Add a class to the selected elements for styling
selectedItems.addClass("selected");
});
</script>
<style>
.selected {
background-color: yellow;
}
</style>
</body>
</html>
In this example, we have an unordered list (<ul>
) containing five list items (<li>
). We use the :lt()
selector to select the first two list items with an index less than 2 (index 0 and index 1). We then add a class called “selected” to these two items to apply a yellow background to them.
When you run the code, you will see that the first two list items are highlighted with a yellow background.
The :lt()
selector is helpful when you want to target specific elements based on their position in the DOM. It allows you to select elements up to a certain index, providing you with fine-grained control over which elements to manipulate or style.