示例HTML:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero.</p>
<p><img src="..." alt=""/></p>
<p><iframe width="" height="" src="...">....</iframe></p>
<p> Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urn</p>
如果可能,如何使用纯javascript有效地获取包含标签而非文本的p标签?
结果应该是:
<p><img src="..." alt=""/></p>
<p><iframe width="" height="" src="...">....</iframe></p>
我接触过这种方式:
var ptags = document.querySelectorAll(".container p");
for(var i = 0; i<ptags.length; i++) {
if(ptags[i].querySelectorAll("img, iframe").length > 0) { .... }
}
答案 0 :(得分:1)
假设您正在使用实际的HTML内容,您可以使用document.querySelectorAll()
函数来获取所有段落,然后使用filter()
函数过滤掉那些不包含任何子元素的函数:
// Grab an array of all of your <p> elements
var paragraphs = Array.prototype.slice.call(document.querySelectorAll('p'), 0);
// Filter out those paragraphs that do not contain any elements
paragraphs = paragraphs.filter(function(p){ return p.childElementCount > 0; });
根据您的修改,您只需检查循环中每个元素的childElementCount
属性:
for(var i = 0; i < ptags.length; i++) {
// Check if this element has children
if(ptags[i].childElementCount > 0) {
// This has children, do something
}
}