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 wrap first few items in div using jQuery?
To wrap first few items in div, use the :lt selector and to wrap, use the wrapAll() method. The :lt() selector selects elements at an index less than the specified number, while wrapAll() wraps all matched elements together with a single wrapper element.
The :lt() selector is zero-indexed, meaning :lt(4) selects the first 4 elements (indices 0, 1, 2, and 3). This makes it perfect for targeting a specific number of items from the beginning of a collection.
Example
You can try to run the following code to learn how to wrap first few list items in div using jQuery −
<!DOCTYPE html>
<html>
<head>
<title>jQuery wrap() method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.demo {
border: 3px dashed blue;
margin: 5px;
padding: 10px;
background-color: #f0f8ff;
}
li {
margin: 5px 0;
}
</style>
</head>
<body>
<ul class="myclass">
<li>India</li>
<li>US</li>
<li>UK</li>
<li>Australia</li>
<li>Bangladesh</li>
<li>Nepal</li>
<li>Bhutan</li>
</ul>
<script>
$(document).ready(function() {
$('ul.myclass > li:lt(4)').wrapAll('<div class="demo"></div>');
});
</script>
</body>
</html>
In this example, the selector ul.myclass > li:lt(4) targets the first 4 list items (indices 0, 1, 2, and 3) within the unordered list with class "myclass". The wrapAll() method then wraps these selected elements with a div having the class "demo".
The output will show the first four list items (India, US, UK, Australia) wrapped together in a div with a blue dashed border and light blue background, while the remaining items (Bangladesh, Nepal, Bhutan) remain unwrapped.
Alternative Approach
You can also use the slice() method for more complex scenarios −
$(document).ready(function() {
// Wrap first 3 items
$('ul.myclass > li').slice(0, 3).wrapAll('');
});
Conclusion
Using jQuery's :lt() selector with wrapAll() method provides an efficient way to wrap the first few elements in a collection with a single container div. This technique is particularly useful for grouping related content or applying special styling to the initial items in a list.
