Reputation:
I have few div elements having id as 'name_a_1', 'name_a_2', 'name_b_3' so on. I want to remove all divs except the first name, which starts from 'name_a_' using JQuery or plain JS?
I successfully tried accessing first and last elements by following JQuery, but how can I access all elements except first?
$('[id^="name_a_"]').first()
$('[id^="name_a_"]').last()
Upvotes: 3
Views: 1080
Reputation: 133403
You can use combination :not()
and :first
selector to target all element except first.
$('[id^="name_a_"]:not(:first)').remove()
or, :gt(index)
selector
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
var hasValue = $('[id^="name_a_"]').filter(function(){
return $(this).val().trim() !== '';
}).length > 0;
Upvotes: 6
Reputation: 91
You can also use the .not
to exclude the first div:
$('div[id^=name_a]').not(':eq(0)').remove();
Upvotes: 1
Reputation: 164764
Plain JS example using Array.prototype.slice
to get all matching elements except for the first.
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>
Upvotes: 2