How to use jQuery to insert a <DIV> wrapped in a variable number of children?

I have an ASP.Net code similar to the following (this is inside FIELDSET):

<ol>
    <li>
        <label>Some label</label>
        <one or more form controls, ASP.Net controls, labels, etc.>
    </li>
    <li>
        <label>Another label</label>
        <... more of the same...>
    </li>
    ...
</ol>

I try to keep my markup as clean as possible, but I decided that for various reasons I need to wrap the DIV around everything in the list item after the first label, for example:

<ol>
    <li>
        <label>Some label</label>
        <div class="GroupThese">
           <one or more form controls, ASP.Net controls, labels, etc.>
        </div>
    </li>
    <li>
        <label>Another label</label>
        <div class="GroupThese">
            <... more of the same...>
        </div>
    </li>
    ...
</ol>

I would prefer to do this with "unobtrusive Javascript" via jQuery instead of clogging my page with extra markup so that I can keep the form semantically "clean".

I know how to write a jQuery selector to go to the first label in each element of the $ list ("li + label") or use: first-child. I also know how to insert things after a selection.

What I cannot understand (at least it's late at night) is how to find everything after the first label in the list item (or basically everything in the list item, except the first label, will be another way of doing this) and wrap it The div around this is the document readiness function.

UPDATE:

Owen code worked after I removed single quotes from:

$ ('this')
and set the correct decentralized selector:
$ ("li label: first-child")
to select only the first label that appears after the list item.

Here is what I did:

$(document).ready(function() {

    $('li label:first-child').each(function() {
        $(this).siblings().wrapAll('<div class="GroupThese"></div>');
    });
});
+3
source share
2 answers

edit : fixed code (see old code in change history and comments for more information)

ok this should work:

$('li label:first-child').each(function() {
    $(this).siblings().wrapAll('<div class="li-non-label-child-wrapper">');
});

from

<li>
    <label>Some label</label>
    <div>stuff</div>
    <div>other stuff</div>
</li>
<li>
    <label>Another label</label>
    <div>stuff3</div>
</li>

gives:

<li>
    <label>Some label</label>
    <div class="li-non-label-child-wrapper">
      <div>stuff</div>
      <div>other stuff</div>
    </div>
</li>
<li>
    <label>Another label</label>
    <div class="li-non-label-child-wrapper">
      <div>stuff3</div>
    </div>
</li>
+5

, <li> , .

var $div = $('li').wrapInner('<div></div>').children('div');
$div.children('label').prependTo($div.parent());
+3

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


All Articles