JQuery - insert div between specific elements
HTML:
<div class="row">
<div class="A"></div>
<div class="B"></div>
<div class="C"></div>
<div class="D"></div>
</div>
<div class="row">
<div class="A"></div>
<div class="B"></div>
<div class="C"></div>
<div class="D"></div>
</div>
What I want to achieve:
<div class="row">
<div class="newDiv">
<div class="A"></div>
<div class="B"></div>
<div class="C"></div>
</div>
<div class="D"></div>
</div>
<div class="row">
<div class="newDiv">
<div class="A"></div>
<div class="B"></div>
<div class="C"></div>
</div>
<div class="D"></div>
</div>
I tried the following code: Include everything in one, ok, but I can't take D outside of the duplicate content.
jQuery('.row').wrapInner('<div class="newDiv"></div>');
And it is not possible to add HTML without tags close together.
jQuery('.A').before('<div class="newDiv">')
jQuery('.D').before('</div>')
+3
source to share
4 answers
Use your code for each div with .each()
for example:
$(document).ready(function(){
$("div[class^=row]").each(function(){
$(this).wrapInner('<div class="newDiv"></div>');
$(this).find(".A").before('<div class="conteneur-produit">')
$(jQuery(this).find(".D")).insertAfter($(this).find('.newDiv'))
});
});
+1
source to share
Here's a demo: https://jsfiddle.net/7a60jz07/
$('.row').each(function(){
var newdiv = $('<div class="newDiv">');
var lastdiv = $(this).children().last();
$(this).append(newdiv);
newdiv.append($(this).children());
newdiv.after(lastdiv);
})
+1
source to share