将类添加到grandgrandparent没有“display:none”样式的元素

时间:2013-07-03 17:57:13

标签: jquery jquery-selectors addclass

使用jQuery如果他的祖父母没有class属性

html就像这样(我强烈要求 添加select):

style="display:none"

此处我希望class添加到<div style"display:none"> <div> <div> <select></select> </div> </div> </div> 元素:

class

有可能这样做吗?

4 个答案:

答案 0 :(得分:3)

试试这个(祖父母):

$('select').each(function(){
    var grandparent = $(this).parent().parent();
    if(grandparent.is(':visible')) { //grandparent is not hidden
       // do something
    }
    else {
       // do something else
    }
});

试试这个(对于曾祖父母):

$('select').each(function(){
    var g_grandparent = $(this).parent().parent().parent();
    if(g_grandparent.is(':visible')) { //great-grandparent is not hidden
       // do something
    }
    else {
       // do something else
    }
});

答案 1 :(得分:2)

或者这个

$("select").filter(function(){
    return $(this).parent().parent().parent().is(":visible");
}).addClass("visible");

http://jsfiddle.net/2Qu7r/

答案 2 :(得分:1)

首先添加缺少的等号:

style="display:none"

那么你可以这样做:

$('select').addClass(function() {
    return $(this).parents().eq(2).is(':visible') ? 'myClass' : '';
});

FIDDLE

答案 3 :(得分:0)

这个怎么样?这会找到select的祖父母,检查可见性,然后将新类添加到select中:

var element = $("select").parent().parent().parent();
if(element.is(":visible")) {
    element.find("select").addClass("new-added-class");
}

JSFIDDLE

上查看