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.
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')) {
// .....
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.