Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to exclude first and second element from jQuery selector?
To exclude first and second element from jQuery, use the slice() method. The slice() method creates a subset of matched elements by specifying a start index, effectively removing elements from the beginning of the selection.
Syntax
The basic syntax for excluding elements using slice() is ?
$(selector).slice(start, end)
Where start is the index from which to begin the selection. To exclude the first two elements, use slice(2) since jQuery uses zero-based indexing.
Example
You can try to run the following code to exclude first and second element from jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('p').slice(2).css('font-size', '24px');
});
</script>
</head>
<body>
<p>Java</p>
<p>C++</p>
<p>Ruby</p>
<p>Groovy</p>
</body>
</html>
In this example, the first two paragraphs (Java and C++) remain with default font size, while the third and fourth paragraphs (Ruby and Groovy) will have their font size changed to 24px.
Conclusion
The slice() method provides an efficient way to exclude specific elements from a jQuery selection by specifying a starting index, making it perfect for skipping the first few elements in a set.
