How to wrap two adjacent elements in a containing div using jQuery?


To wrap two adjacent elements, loop through each myclass, add it to array and determining the next element has a .myclass. You can try to run the following code to learn how to wrap two adjacent elements in a containing div −

Example

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var result = [];
   
    $('.myclass').each(function() {
        var box2 = $(this).next().hasClass('myclass');
       
        result.push($(this));
       
        if(!box2)
        {
            var container = $('<div class="result"></div>');
            container.insertBefore(result[0]);
            for(x=0;x<result.length;x++)
            {
                result[x].appendTo(container);
            }
            result = [];
        }
    })
})
</script>

</head>
<style>
 div.result {
   background:#4486EC;
 }
</style>
<body>

<p>Demo text</p>

<div class="myclass">...</div>
<div class="myclass">...</div>

<p>This is demo text.</p>

<div class="myclass">...</div>
<div class="myclass">...</div>
</body>
</html>

Updated on: 17-Feb-2020

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements