2016-04-25 62 views
-1

例HTML而不是文本:檢查元素包含子標籤使用JavaScript

<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> 

我怎樣纔能有效地得到這些p標籤包含了使用純JavaScript代碼,而不是文本,如果可能的話?

的結果應該是:

<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) { .... } 
} 

回答

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 
    } 
} 
+0

感謝利昂,childElementCount財產是我一直在尋找。 – g13