找不到直接元素

时间:2017-11-09 14:00:23

标签: html css

编辑:请注意,父div的数量可能会有所不同。它可以是一个或多个。

我正在尝试所有内容以获取包含标签的<div><div>的父级rat。因此,在这种情况下,必须返回最外面的<div>

<div> --> Should be returned
    <div>  
        <div class="item box1" id="box1">1</div>
        <div class="item" id="box2">2</div>
        <div class="item" id="box3">3</div>
        <div class="item rat" id="box4">4</div> 
    </div>
    <label>Im the original parent</label>
</div>

当我为每个div添加类属性并使用closest()时,可以很容易地完成,但在这种情况下,我没有可以使用的唯一选择器。

或者我们可以这样做:使用上面的示例找到<div>rat类最近的标签:

$('.rat') -> selector

3 个答案:

答案 0 :(得分:1)

递归方法最适合您所需的行为:

function getParentWithLabel(className) {
    function climbRecusively(node) {
        const parent = node.parent();
        return (parent.find('> label').length ? parent : climbRecusively(parent));
    }
    return climbRecusively($(`.${className}`));
}

$(function() {
    getParentWithLabel('rat').css('background-color', 'grey');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>  
        <div class="item box1" id="box1">1</div>
        <div class="item" id="box2">2</div>
        <div class="item" id="box3">3</div>
        <div class="item rat" id="box4">4</div> 
    </div>
    <label>Im the original parent</label>
</div>

我希望这会有所帮助。

答案 1 :(得分:0)

如果你在全局jQuery中应用你的风格会更容易,比如:

$('.rat').parent().next();

答案 2 :(得分:0)

试试这个

   var parentEls = $( ".rat" ).parents();

parentEls.each(function (i, obj) {
    if($(obj).find( "> label" ).length){
    console.log($(obj).attr('class'));
  }
});

完整示例:http://jsfiddle.net/harshakj89/ey00czfn/1/