
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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>
Advertisements