Javascript 纯js中的jquery remove()等价物?

Javascript 纯js中的jquery remove()等价物?,javascript,jquery,ecmascript-6,Javascript,Jquery,Ecmascript 6,我尝试删除jquery代码并将其转换为纯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.

我尝试删除jquery代码并将其转换为纯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

function remove(element) {
element.parentNode.removeChild(element); 
}
并将其用作

<div>
<a href="#" onClick="remove(this.parentNode)">...</a>
</div>

区别在于
jQuery
删除与选择器匹配的所有项,而纯JS(在您的版本中)删除第一个找到的节点。要删除所有内容,可以执行以下操作

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

使用现代javascript,这应该是可行的:

仔细看——这不是jQuery

//const$=document.querySelector.bind(document);//itm.parentNode.removeChild(itm));
将$和$$行放在javascript项目的顶部,这样可以节省一些输入,并混淆jQuery

参考资料:


也许你可以试试
item.parentElement.removeChild
?你能描述一下你在这两种方法中观察到的不同行为吗?
//const $ = document.querySelector.bind(document); //<== not needed in _this_ example
const $$ = document.querySelectorAll.bind(document);
$$('[type=item]').forEach( itm => itm.parentNode.removeChild(itm) );