简体   繁体   中英

jquery remove() equivalent in pure 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

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

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);
}

Using modern javascript, this should work:

Look closely - this is not jQuery

//const $ = document.querySelector.bind(document); //<== not needed in _this_ example
const $$ = document.querySelectorAll.bind(document);
$$('[type=item]').forEach( itm => itm.parentNode.removeChild(itm) );

Put the $ and $$ lines at the top of your javascript project, and it should save you some typing - and confuse the jQuery-ites.

References:

https://plainjs.com/javascript/selecting/select-dom-elements-by-css-selector-4/

function remove(element) {
element.parentNode.removeChild(element); 
}

and use it as

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

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.

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