Javascript得到nextSibling不是类“foo”

时间:2010-11-09 10:31:46

标签: javascript

我需要获得元素的下一个兄弟,但它不应该有类“foo”。在jQuery中,这将是:

myEl.next("div.goodClass")
or
myEl.next().not(".foo")

可以使用 nextSibling 完成吗?

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式检查 nextSibling className 属性:

if (/(?:^|\s)foo(?:\s|$)/.test(el.nextSibling.className)) {
    // next sibling has foo class
}

如果你想找到没有那个类的下一个元素,你可以这样做:

var el = document.getElementById("myEl");

while (el = el.nextSibling) {
    if (!(/(?:^|\s)foo(?:\s|$)/.test(el.className)))
        break;
}

// el is either null, or an element that doesn't have the foo class

答案 1 :(得分:0)

试试这个:

if (elem.nextSibling && !/(?:^|\s+)foo(?:\s|$)/.test(elem.nextSibling.className)) {
    // there is a next sibling that does not have the class foo
}

答案 2 :(得分:0)

试试这段代码,

x=myEl.nextSibling;
while (x.nodeType!=1)
{
    if(x.className=="foo"){
       x=x.nextSibling;
    }
}
return x;
相关问题