How to achieve this in JavaScript?
function prevAll (element) {
// some code to take all siblings before element?
return elements;
};
With .previousElementSibling, you get the previous node that's an actual element (not a text node or comment).
function prevAll(element) {
var result = [];
while (element = element.previousElementSibling)
result.push(element);
return result;
}
The .previousElementSibling property can be polyfilled in IE8 if needed.
I should note that IIRC, jQuery returns the elements in document order. If that's the case and if that's what you need, just .reverse() the array when you return it.
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