jquery 查找考虑父元素的元素

jquery find element considering parent

如何找到考虑父节点的元素?示例:

<ul class="level-3">
     <li class="item-1">1</li>
     <li class="item-2">2</li>
     <li class="item-3">3</li>
</ul>
var $ul = $('.ul');
console.log($ul.find('.item-1')) - // found - OK

如果找到

console.log($ul.find('.level-3')) - // not found - WHY ???

您可以使用 soma 类 jQuery 函数来执行此操作:

Closest: 找到与选择器匹配的定位元素。

The .closest() method begins its search with the element itself before progressing up the DOM tree

Parents:遍历 DOM 树寻找所有匹配选择器的 parents。

is: 检查元素是否匹配选择器

$ul.closest(".level-3")

假设 UL 为元素

您无法找到它,因为 level-3 不是 ul 的 child。

根据您当前的 HTML,您需要使用 .filter()

Reduce the set of matched elements to those that match the selector or pass the function's test.

代码

var $ul = $('ul'); 
$ul.filter('.level-3')

在您看来,您没有“.level-3”class。简单地说,你可以使用 jquery 来做到这一点。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        alert($("ul").find('.item-3').text());
    });
});
</script>
</head>
<body>
<ul class="level-3">
     <li class="item-1">1</li>
     <li class="item-2">2</li>
     <li class="item-3">3</li>
</ul>

<button id="btn1">Show level 3 Text</button>

</body>
</html>