Skip to content Skip to sidebar Skip to footer

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 c

Solution 1:

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

Solution 2:

Using modern javascript, this should work:

Look closely - this is not jQuery

//const $ = document.querySelector.bind(document); //<== not needed in _this_ exampleconst $$ = 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/

Solution 3:

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

and use it as

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

Post a Comment for "Jquery Remove() Equivalent In Pure Js?"