要像jQuery一样使用prevAll的JavaScript? [英] JavaScript to use prevAll like jQuery?

查看:37
本文介绍了要像jQuery一样使用prevAll的JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中实现此目标?

How to achieve this in JavaScript?

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

推荐答案

使用 .previousElementSibling ,您将获得作为实际元素的前一个节点(而不是文本节点或注释).

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;
}

如果需要,可以在IE8中填充 .previousElementSibling 属性.

The .previousElementSibling property can be polyfilled in IE8 if needed.

我应该注意,IIRC,jQuery按文档顺序返回元素.如果是这样,而这正是您所需要的,则在返回数组时只需 .reverse()即可.

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.

这篇关于要像jQuery一样使用prevAll的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆