首页 > 解决方案 > 如何从具有特定 ID 的列表中删除元素

问题描述

我有两个列表,我想删除所有li标签,除了那些包含输入元素的 li 标签,-allid. 这是我可以在 jQuery 中使用选择器实现的吗?可能使用非选择器?

这是我目前拥有的:$("#search-filter-column ul li").remove();

<ul>
   <li>
       <input id="filter-types-all" name="filter-types-all" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-types-suv" name="filter-types-suv" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-types-special" name="filter-types-special" type="checkbox" checked="checked">
   </li>
</ul>


<ul>
   <li>
       <input id="filter-company-all" name="filter-company-all" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-company-1" name="filter-company-1" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-company-2" name="filter-company-2" type="checkbox" checked="checked">
   </li>
</ul>


<ul>
   <li>
       <input id="filter-location-1" name="filter-location-1" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-location-2" name="filter-location-2" type="checkbox" checked="checked">
   </li>
   <li>
       <input id="filter-location-3" name="filter-location-3" type="checkbox" checked="checked">
   </li>
</ul>

标签: javascriptjqueryhtml

解决方案


您可以测试元素内部的元素,然后使用CSS 伪类“ends-with”属性选择器 ( )以及“starts-with” ( ) ,而不是搜索<li>元素然后测试其内容属性选择器排除任何不相关的元素。然后,您可以使用Jquery方法删除任何匹配元素的父级。inputli:not()$=^=inputli.parent()

// Remove all input elements that are descendants of an <li> that don't have
// an id that ends with ($=) "all" or an id that starts with "filter-location-".
$("#search-filter-column ul > li input:not([id$='-all']):not([id^='filter-location-'])").parent().remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search-filter-column">
<ul>
   <li>
     <input id="filter-types-all" name="filter-types-all" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-types-suv" name="filter-types-suv" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-types-special" name="filter-types-special" type="checkbox" checked="checked">
   </li>
</ul>
<ul>
   <li>
     <input id="filter-company-all" name="filter-company-all" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-company-1" name="filter-company-1" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-company-2" name="filter-company-2" type="checkbox" checked="checked">
   </li>
</ul>
<ul>
   <li>
     <input id="filter-location-1" name="filter-location-1" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-location-2" name="filter-location-2" type="checkbox" checked="checked">
   </li>
   <li>
     <input id="filter-location-3" name="filter-location-3" type="checkbox" checked="checked">
   </li>
</ul>
</div>


推荐阅读