问题
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