Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to use prevAll like jQuery?

How to achieve this in JavaScript?

function prevAll (element) {
    // some code to take all siblings before element?
    return elements;
};

1 Answers

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.

like image 63
4 revsuser1106925 Avatar answered Nov 29 '25 10:11

4 revsuser1106925



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!