Jerry Svensson Jerry Svensson - 6 months ago 10
jQuery Question

How do wrap these groups of li elements in ul containers?

Goal:

First wrap the elements before the first empty div in a set of

ul
containers and then do the same for the elements that are between empty
li
s.

The empty element can be included in the container or removed.

Question:

How do I wrap these sets of elements in a set of
ul
containers if I can't target the class?

Problem:

1) The only variable I can use is the empty
li
because there will be a different amount of elements in each container.

2) The html doesn't end with an empty
li
.

HTML:

<div class="body">
<fieldset>
<ol>

<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>


wrap elements above

<li>&nbsp;</li>


wrap elements below until the next empty
li


<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>
<li>&nbsp;</li>


wrap elements below until the next empty
li


<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>
<li>
<h6>Customer Details</h6>
</li>

</ol>
</fieldset>
</div>

Answer

This is completely untested as I am on my phone, but I'm happy to update if there's syntax errors. It relies on you being able to select/identify the parent to the HTML you have provided (assuming you have failed to add the final empty divider referred to in a comment above).

// Get the known parent to this mess of li elements
var knownParent = $(...);
// Give the empty li elements an identifying class
knownParent.find("li").filter(function(){ return $(this).html().match(/&nbsp;/) !== null; }).addClass("_liDivider");
// Wrap everything between the dividers with a ul element
$.each(
  $("._liDivider:not(:last-child)"), function() {
      $(this)
        .nextUntil("._liDivider")
        .wrap("<ul></ul>");
    }
);
// Now deal with the orphaned li elements before the first divider
knownParent.find("li:first-of-type").nextUntil("._liDivider").wrap("<ul></ul>");
Comments