'jQuery: Wrap sibling divs of the same class with flexible selector
I'm looking to target all siblings of the same class name together into a container.
In this HTML,
<div class="pink"></div>
<div class="pink"></div>
<div class="pink"></div>
<div class="red"></div>
<div class="red"></div>
<div class="pink"></div>
I want all .pink
divs next to each other to be wrapped in a .pinkwrap
container, even if .pink
doesn't have any siblings, like the last line.
All other divs are left untouched.
Ideal result:
<div class="pinkwrap">
<div class="pink"></div>
<div class="pink"></div>
<div class="pink"></div>
</div>
<div class="red"></div>
<div class="red"></div>
<div class="pinkwrap">
<div class="pink"></div>
</div>
Here's what I've attempted in jQuery so far:
var towrap = $(".pink");
towrap.each(function(){
$(this).not(".pink + .pink").each(function(){
$(this).nextUntil(":not(.pink)").addBack().wrapAll('<div class="pinkwrap">');
});
})
This works, but if I only wanted to change the selector in my towrap
variable without adjusting it in subsequent lines, how would I rewrite .not(".pink + .pink")
and .nextUntil(":not(.pink)")
to fit this?
What I've tried:
var towrap = $(".pink");
towrap.each(function(){
$(this).not(towrap + towrap).each(function(){
$(this).nextUntil().not(towrap).addBack().wrapAll('<div class="pinkwrap">');
});
})
But this obviously doesn't work. Here's the jsfiddle. I'm open to any suggestions and links to previous answers in case I missed any!
Solution 1:[1]
I figured it out.
The solution was to declare the div as a string, rather than a selector: var towrap = ".pink";
var towrap = ".pink";
$(towrap).each(function(){
$(this).not(towrap + "+" + towrap).each(function(){
$(this).nextUntil(":not(" + towrap + ")").addBack().wrapAll('<div class="pinkwrap">');
});
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | deadweig-ht |