[英]JQuery: how to remove all div elements except first containing sub-string as 'id' tag?
I have few div elements having id as 'name_a_1', 'name_a_2', 'name_b_3' so on. 我有几个div元素,ID为'name_a_1','name_a_2','name_b_3'等等。 I want to remove all divs except the first name, which starts from 'name_a_' using JQuery or plain JS?
我想删除除名字之外的所有div,它使用JQuery或普通JS从'name_a_'开始?
I successfully tried accessing first and last elements by following JQuery, but how can I access all elements except first? 我成功尝试通过遵循JQuery访问第一个和最后一个元素,但是如何访问除了第一个之外的所有元素?
$('[id^="name_a_"]').first()
$('[id^="name_a_"]').last()
You can use combination :not()
and :first
selector to target all element except first. 您可以使用组合
:not()
和:first
选择器来定位除first之外的所有元素。
$('[id^="name_a_"]:not(:first)').remove()
or, :gt(index)
selector 或,
:gt(index)
选择器
Select all elements at an index greater than index within the matched set.
选择匹配集中索引大于索引的所有元素。
$('[id^="name_a_"]:gt(0)').remove()
To check if element have value, .filter()
can be used 要检查元素是否具有值,可以使用
.filter()
var hasValue = $('[id^="name_a_"]').filter(function(){
return $(this).val().trim() !== '';
}).length > 0;
Plain JS example using Array.prototype.slice
to get all matching elements except for the first. 使用
Array.prototype.slice
普通JS示例获取除第一个之外的所有匹配元素。
Array.prototype.slice.call(document.querySelectorAll('[id^="name_a_"]'), 1) .forEach(elt => elt.parentNode.removeChild(elt))
<ul> <li id="name_a_1">name_a_1</li> <li id="name_a_2">name_a_2</li> <li id="name_a_3">name_a_3</li> <li id="name_a_4">name_a_4</li> </ul>
您还可以使用.not
排除第一个div:
$('div[id^=name_a]').not(':eq(0)').remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.