简体   繁体   English

在 Vanilla JavaScript 中过滤掉父元素中的所有子元素

[英]Filter out all child elements from parent in Vanilla JavaScript

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 .我正在尝试在 Vanilla JavaScript 中查询 DOM,以从具有 class icon的父节点中过滤掉包含img标签的所有元素。 Example:例子:

After writing query it should return two elements <span> and <a> :编写查询后,它应该返回两个元素<span><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,我可以使用以下方法轻松实现:

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

I am finding it bit challenging to implement the same in Vanilla JavaScript.我发现在 Vanilla JavaScript 中实现相同的功能有点挑战。

Selecting all .icon , loop through them, filter out all that contain img选择所有.icon ,遍历它们,过滤掉所有包含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. @qiAlex - 感谢您让这看起来如此简单。 I have to make few adjustments to make it work in IE.我必须做一些调整才能让它在 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')) {
        // .....
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM