How to find the deepest ul/ol with list items in a nested list

社会主义新天地 提交于 2021-01-29 22:13:53

问题


I am trying to clean up bulleted lists generated by another program which has created nested lists which are unnecessary. I need to remove them. Here are 2 examples...

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Document</title>
</head>

<body>
  <ul>
    <ul>
      <li>
        <ul>
          <li>List Item 1</li>
          <li>List Item 2</li>
        </ul>
      </li>
    </ul>
  </ul>
   <ul>
  <li>
    <ul>
      <li>
        <ul>
          <li>
            <ol>
              Prep Steps
              <li>Step 1</li>
              <li>Step 2</li>
              <li>Step 3</li>
            </ol>
            <ul>
              Other things to note
              <li>Another LI 1</li>
              <li>Another LI 2</li>
              <li>Another LI 3</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</body>

</html>

I need to find the ul/ol with valid list item context (any text) and remove all the extraneous uls wrapped around them. To do this, I was trying to find the deepest ul that has list items. I tried a few selector like $("ul:has(li)"), but this returns all the parent uls also.


回答1:


Try this:

    $('ul,ol').not(':has(ul,ol)')

$('ul,ol').not(':has(ul,ol)').each((index,list) => console.log(list));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <ul>
      <li>
        <ul>
          <li>List Item 1</li>
          <li>List Item 2</li>
        </ul>
      </li>
    </ul>
  </ul>
  <ul>
    <li>
      <ul>
        <li>
          <ul>
            <li>
              <ol>
                <li>Another LI 1</li>
                <li>Another LI 2</li>
                <li>Another LI 3</li>
              </ol>
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>


来源:https://stackoverflow.com/questions/63770965/how-to-find-the-deepest-ul-ol-with-list-items-in-a-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!