Jef*_* B. 15 jquery jquery-selectors
我在Stack Overflow上发现了许多相关的东西,但不适用于我的情况.
在这个例子中,我需要检查一个元素是否包含另一个元素,如果是,则附加一些东西.
$(".bt_repondre").click(function(){
comment = $(this).parent().parent().parent();
//I want to check if comment contains a .comment_full element, if no, append.
comment.append('add');
});
Run Code Online (Sandbox Code Playgroud)
希望你能帮助我,我尝试了很多东西......
Ble*_*der 33
你可以使用.has和.length:
if (comment.has('.comment_full').length) {
// It has that element
}
Run Code Online (Sandbox Code Playgroud)
.find将迭代所有后代,但.has一旦找到与选择器匹配的后代,它将停止.它可能运行得更快.
.length 只检查生成的元素集的长度是否为非零.
Nel*_*son 16
只需使用.find()并检查是否返回一个元素,如下所示:
$(".bt_repondre").click(function(){
comment = $(this).parent().parent().parent();
if (! comment.find('.comment_full').length) {
comment.append('add');
}
});
Run Code Online (Sandbox Code Playgroud)
大多数答案都是不正确的.您必须传递一个DOM节点而不是$ .contains的jQuery元素才能按照https://api.jquery.com/jQuery.contains/正常工作.
例如,这是您确定是否$('#a')包含的方式$('#b).
HTML:
<div id="a">
<div id="b"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
var $a = $('#a');
var $b = $('#b');
var contains = $.contains($a.get(0), $b.get(0));
console.log('contains', contains);
// outputs `true`
Run Code Online (Sandbox Code Playgroud)