0

Question

What are ways to add dynamic elements to wrap list items and apply a class?

Current research

I found this on the official docs from jQuery.

Which gave an example

<script>
    $( "span:nth-of-type(2)" )
    .append( "<span> is 2nd sibling span</span>" )
    .addClass( "nth" );
</script>

But that only discussed adding a class to an individual element. I want to wrap multiple elements

Default code with generated items

<ul>
    <!-- These items will be dynamically generated-->
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
    <li>Fifth</li>
    <li>Sixth</li>
</ul>

What the current code would produce

enter image description here

Desired outcome

<ul>
    <div class="row">
        <li>First</li>
        <div class="right">
            <li>Second</li>
            <li>Third</li>
        </div>
    </div>
    <div class="row">
        <div class="left">
            <li>Fourth</li>
            <li>Fifth</li>
        </div>
        <li>Sixth</li>
    </div>
</ul>

What the desired code would produce (CSS styling defined elsewhere)

enter image description here

Community
  • 1
  • 1
JGallardo
  • 11,074
  • 10
  • 82
  • 96
  • if the wrapping pattern is going to be the same and not random then how about using the `documentFragment` to avoid the multiple reflow and improved performance too. – Muhammad Omer Aslam Feb 12 '18 at 20:47
  • 1
    The HTML of the desired outcome is invalid – j08691 Feb 12 '18 at 20:52
  • As you see you can chain `append()` method, so add all your elements, and then apply class on desired selectors. – Striped Feb 12 '18 at 20:53
  • @j08691 so probably better to just have all `
    ` as opposed to `
  • `s?
– JGallardo Feb 12 '18 at 20:54
  • `.wrapall()` is probably the function you're looking for. – Barmar Feb 12 '18 at 21:32
  • @Barmar from what I have found so far. I can wrap all of the same elements like `$( "p" ).wrapAll( document.createElement( "div" ) );` but i have a gap in information for then wrapping specific numbered items. – JGallardo Feb 12 '18 at 21:46
  • `$("p").slice(0, 3).wrapAll("
    ")` will wrap the first 3.
    – Barmar Feb 12 '18 at 21:50
  • See https://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div/3366539#3366539 – Barmar Feb 12 '18 at 21:51