Fix invalid nested lists with jQuery

Viewed 78

I have been left with a rather large legacy pile of HTML. I have multiple lists that have sub lists that have not been incorporated into list item, although this renders correctly, it still causes a problem in accessibility testing. Is there a jQuery method that allow me to correct this, until I can convince the content providers to do it properly?

<ul>
    <li>list</li>
    <li>list</li>
       <ul class="shouldBeSublist">
        <li>list</li>
        <li>list</li>
        <li>list</li>
      </ul>
    <li>list</li>
</ul>

last failed attempt...

$("ul ul").append(function () {
                return this.closest("li");
});

wanted outcome...

<ul>
    <li>list</li>
    <li>list
       <ul class="shouldBeSublist">
        <li>list</li>
        <li>list</li>
        <li>list</li>
      </ul>
    **</li>**
    <li>list</li>
</ul>
1 Answers

Select only lists which are children of lists and use jQuery's appendTo() method to move them to the previous list element:

$('ul > ul').each(function() {
  $(this).appendTo($(this).prev('li'));
});

https://api.jquery.com/appendto/

Demo

Related