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. You can try to run the following code to learn how to wrap first few list items in div using jQuery −

Example

Live Demo

<html>
   <head>
      <title>jQuery wrap() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
           $('ul.myclass > li:lt(4)').wrapAll('<div class="demo"></div>')
         });
      </script>

      <style>
         .demo {
           border: 3px dashed blue;
           margin: 5px;
         }      
      </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>

   </body>
</html>

Updated on: 14-Feb-2020

496 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements