如果div包含< p>,则jQuery会返回true或false。标签 [英] jQuery return true or false if a div contains a <p> tag
本文介绍了如果div包含< p>,则jQuery会返回true或false。标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们看看:
< DIV>< P>这div包含AP标记< / P>< / DIV>
< div>这一个不是< / div>
如果div包含特定值,如何为布尔值赋值(true或false) ?像在上面的例子中p标签
解决方案
$(DIV:具有(对) )addClass( 有段);
会为包含p个子元素的所有div添加一个类。如果这些段落不是直接的孩子,那么它们就不会收到它们。
注意:这样做:
$(div p)。addClass(has-paragraph);
会将类添加到段而不是div。你可以通过这样做来解决这个问题:
$(div p)。parents(div)。addClass(有段);
但这会捕获多个div祖先。你可以这样做:
$(div p)。parents(div:first)。addClass(has -段);
解决这个问题。
或更多编程:
$( DIV)每个(函数(){
如果($(本)。 find(p)。length> 0){
// do stuff
}
});
Let's see:
<div><p>this div contains a p tag</p></div>
<div>this one is not</div>
How do i assign a variable with a boolean value (true or false) if a div contains a specific tag like p in the above example?
解决方案
$("div:has(p)").addClass("has-paragraph");
will add a class to all divs that contain p children. If the paragraphs aren't direct children, this won't pick them up.
Note: doing this:
$("div p").addClass("has-paragraph");
will add the class to the paragraph not the div. You can fix that by doing this:
$("div p").parents("div").addClass("has-paragraph");
but this will catch multiple div ancestors. You could do this:
$("div p").parents("div:first").addClass("has-paragraph");
to fix that.
Or more programmatically:
$("div").each(function() {
if ($(this).find("p").length > 0) {
// do stuff
}
});
这篇关于如果div包含< p>,则jQuery会返回true或false。标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文