Using jquery elements to group

I have a whole group of elements that I need to group, but due to the fact that it spits out from some mechanism that I cannot change, I need to do this using jquery (which I am pretty familiar with the basics)

Basically, I have tags and divs loaded inside the form element (yes, poor markup, but this is another story). I need to group p tags using the following one or two divs inside a set of fields.

I tried pasting fieldset close and then running the tag before each p-element, but I think the mechanism that sorts it wants to insert legal elements, so it doesn't work

+3
source share
2 answers

, , :

<p>paragraph 1</p>
<div>par1 div1</div>
<div>par1 div2</div>
<p>paragraph 2</p>
<div>par2 div1</div>
<div>par2 div2</div>
<p>paragraph 3</p>
<div>par3 div1</div>
<p>paragraph 4</p>
<div>par4 div1</div>

- :

<fieldset>
 <p>paragraph1</p>
 <div>par1 div1</div>
 <div>par1 div2</div>
</fieldset>
<fieldset>
 <p>paragraph2</p>
 <div>par2 div1</div>
 <div>par2 div1></div>
</fieldset>
.....

, jQuery :

$(function(){   
    $('p').each(function(index,item){
      var nextDiv = $(item).next();
      var followingDiv = $(nextDiv).next('div');
      $(item).wrap("<fieldset id='fieldset" + index + "'></fieldset>");
      $("#fieldset"+index).append(nextDiv).append(followingDiv);
    });
});
+7

@JoseBasillo :

var $wrapper = $('#wrapper');
$wrapper.children('p').each(function(index,item) {
    var $following = $(item).nextUntil('p, fieldset');
    $wrapper.append($('<fieldset>').append(item, $following));
});

<div id="wrapper">
    <p>paragraph 1</p>
        ... (whatever but p or fieldset)
    <p>paragraph 2</p>
        ... (whatever but p or fieldset)
    ... (p followed by whatever but p or fieldset)
</div>

<div id="wrapper">
    <fieldset>
        ... (whatever but p or fieldset)
    </fieldset>
    <fieldset>
        ... (whatever but p or fieldset)
    </fieldset>
    ... (fieldset containg [p followed by whatever but p or fieldset])
</div>

- , , $following:

var $wrapper = $('#wrapper');
$wrapper.children('p').each(function(index,item) {
    $wrapper.append($('<fieldset>').append( item, $(item).nextUntil('p, fieldset') ));
});
+1

Source: https://habr.com/ru/post/1710459/


All Articles