Mike Vierwind
Mike Vierwind

Reputation: 1520

How to group HTML elements by wrapping using jQuery

I have HTML, that I can not change. I can only change the CSS and Javascript. I have HTML with spans and a lot of dl lists.

But, now I want to wrap this HTML. I want to have a div around it. But I want a div to the groups. A group begins with the first span and ends with the last dl.

How can I do this with Javascript / jquery?

<span>Information</span>
<dl></dl>
<dl></dl>
<dl></dl>
<dl></dl>
<span>Specifications</span>
<dl></dl>
<dl></dl>
<dl></dl>
<dl></dl>
<span>Product information</span>
<dl></dl>
<dl></dl>
<dl></dl>
<dl></dl>
<dl></dl>
<dl></dl>

Upvotes: 2

Views: 85

Answers (2)

George
George

Reputation: 36794

Loop through each span and wrap elements from this until next span. If there is no nextUntil() span, it will select all following siblings in the DOM:

$('span').each(function(){
   $(this).nextUntil('span').addBack().wrapAll('<div />')
});

JSFiddle

Upvotes: 6

GhitaB
GhitaB

Reputation: 3437

You can use wrapAll() function. See here examples and documentation: https://api.jquery.com/wrapAll/

Upvotes: 0

Related Questions