g13 g13 - 1 year ago 47
HTML Question

Check if element contains child tag not text using javascript

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

How can I get those p tags efficiently that contain tags instead of text using pure javascript, if possible?

Result should be:

<p><img src="..." alt=""/></p>
<p><iframe width="" height="" src="...">....</iframe></p>

I have approached it, this way:

var ptags = document.querySelectorAll(".container p");
for(var i = 0; i<ptags.length; i++) {
if(ptags[i].querySelectorAll("img, iframe").length > 0) { .... }

Answer Source

Assuming you are working with actual HTML content, you could use the document.querySelectorAll() function to grab all of your paragraphs and then use the filter() function to filter out those that did not contain any child elements :

// 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; });

Based on your edit, you could simply check the childElementCount property of each of your elements in your loop :

for(var i = 0; i < ptags.length; i++) { 
   // Check if this element has children
   if(ptags[i].childElementCount > 0) { 
       // This has children, do something