如果 div 包含 <p> 标签,jQuery 返回 true 或 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/965184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery return true or false if a div contains a <p> tag
提问by user119210
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 包含一个特定的标签,如上例中的 p,我如何分配一个带有布尔值(真或假)的变量?
回答by cletus
$("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.
将向所有包含 p 个孩子的 div 添加一个类。如果段落不是直接子级,则不会选取它们。
Note:doing this:
注意:这样做:
$("div p").addClass("has-paragraph");
will add the class to the paragraphnot the div. You can fix that by doing this:
将类添加到段落而不是 div。你可以通过这样做来解决这个问题:
$("div p").parents("div").addClass("has-paragraph");
but this will catch multiple div ancestors. You could do this:
但这将捕获多个 div 祖先。你可以这样做:
$("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
}
});
回答by karim79
Give your div an ID, then:
给你的 div 一个 ID,然后:
if($('#myDiv p').length) {
alert('I have a paragraph');
}
回答by Daniel A. White
var result = ($('div p').size() > 0);
or
或者
var result = ($('div p').length > 0);
This will grab any p
inside any div
. This is basically what @karim79 has.
这将抓取 anyp
里面的 any div
。这基本上就是@karim79 所拥有的。
回答by glmxndr
This would be my bet :
这将是我的赌注:
$("div").each(function(){
if ($(this).children('p').length>0){
// do stuff, assign boolean if you want
}
});
I assumed you are looking for direct children. If not, use
我假设您正在寻找直系子女。如果没有,请使用
if ($(':has(p)',this).length>0) ...
回答by James van Dyke
Not sure how you want to store your information, but the following code will gather all div tags which contain a p tag.
不确定您想如何存储您的信息,但以下代码将收集所有包含 ap 标签的 div 标签。
$("div:has(p)").each( function () {
# Store what you need here
});
If you have a specific div you want to test the following should work based on a "truthy" value. I'm sure someone can get you exactly a true or false value through some clever means.
如果您有一个特定的 div,您想测试以下内容应该基于“真实”值。我相信有人可以通过一些巧妙的方法让你准确地得到一个真值或假值。
if ( $("#divId:has(p)") ) {
# Do what you need here
}