Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap div around 2 sequential elements in jQuery

Tags:

jquery

I have repeating elements like this:

<dt class="variationTitle">
  Title
</dt>
<dd class="variationName">
  Name
</dd>
<dt class="variationTitle">
  Title
</dt>
<dd class="variationName">
  Name
</dd>

It's a dt tag followed by a dd tag, unfortunately I can't change the HTML directly, but I need to wrap a <div class="variation"> around the title and name so it looks like this:

<div class="variation">
    <dt class="variationTitle">
      Title
    </dt>
    <dd class="variationName">
      Name
    </dd>
</div>
<div class="variation">
    <dt class="variationTitle">
      Title
    </dt>
    <dd class="variationName">
      Name
    </dd>
</div>
like image 759
Jordash Avatar asked Dec 19 '22 20:12

Jordash


1 Answers

One option would be to iterative over each dt element and then select the adjacent dd element and wrap them both using the .wrapAll() method:

$('dt').each(function() {
  $(this).add($(this).next('dd')).wrapAll('<div class="variation"></div>')
});

It works because $(this) is the current dt element, and .add() will add the next dd element to the jQuery object, and .wrapAll() will wrap each element in the jQuery object.

like image 110
Josh Crozier Avatar answered Feb 26 '23 17:02

Josh Crozier