jQuery remove()等价于纯js? [英] jquery remove() equivalent in pure js?

查看:30
本文介绍了jQuery remove()等价于纯js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试删除jquery代码并将其转换为纯js

I try to remove jquery code and convert it to pure js

//old code in jquery
const item = $('[type=item]')
item.text() === '' && $(item).remove()

//new code without jquery
const item = document.querySelector('[type="item"]')
item.innerText === '' && item.parentNode.removeChild(item) // this is problem

但是使用第二个代码块会产生不同的行为,我想我错误地使用了removeChild.

But I got different behavior using the second block of code, I guess I'm using removeChild wrongly.

推荐答案

不同之处在于 jQuery 会删除与选择器和纯JS(在您的版本中)匹配的 all 项目删除第一个找到的节点.要删除 all ,您可以执行以下操作.

The difference is that jQuery removes all items which match selector and pure JS (in your version) removes the first found node. To remove all you can do something like this.

const item = document.querySelectorAll('[type=item]');
for(let i=0,it;it=item[i];++i){
    it.innerText === '' && it.parentNode.removeChild(it);
}

这篇关于jQuery remove()等价于纯js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆