Filter out all child elements from parent in Vanilla JavaScript

Viewed 1639

I am trying to query DOM in Vanilla JavaScript to filter out all elemnts containing the img tags from the parent node with class icon. Example:

After writing query it should return two elements <span> and <a>:

<span class="icon"><a href="#">link</a></span>
<a class="icon" href="#">link</a>

This should not return anything:

<span class="icon"><a href="#"><img src="asdf"></a></span>
<a class="icon" href="#"><img src="asdf"></a>

Using jQuery I can easily achieve this using:

jQuery('.icon').not(':has(img)')

I am finding it bit challenging to implement the same in Vanilla JavaScript.

2 Answers

Selecting all .icon, loop through them, filter out all that contain img

const result = [...document.querySelectorAll(`.icon`)]
  .filter(item => !item.querySelector(`img`))

console.log(result);
<span class="icon"><a href="#">link</a></span>
<a class="icon" href="#">link</a>


<span class="icon"><a href="#"><img src="asdf"></a></span>
<a class="icon" href="#"><img src="asdf"></a>

@qiAlex - Thanks for making this look so simple. I have to make few adjustments to make it work in IE. Below is the code that may help somebody with same requirement:

const iconsArray = document.querySelectorAll('.icon');
Array.prototype.forEach.call(iconsArray, function (element) {
    if (!element.querySelector('img')) {
        // .....
    }
});
Related