Using jQuery how can you select all elements but the last?
<div class='elem'>1</div>
<div class='elem'>2</div>
<div class='elem'>3</div>
For example I want hide div's 1 and 2, but keep three.
To exclude first and second element from jQuery, use the slice() method.
jQuery :not() SelectorThe :not() selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().
Following is the basic syntax for selecting HTML elements and then performing some action on the selected element(s): $(document). ready(function(){ $(selector).
$("div.elem:not(:last)").hide();
or
$("div.elem").not(":last").hide();
You can hide by nth-child of element as defined below.
$("div.elem:not(:nth-child(3))").hide();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With