Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements by class name?

If you prefer not to use JQuery:

function removeElementsByClass(className){
    const elements = document.getElementsByClassName(className);
    while(elements.length > 0){
        elements[0].parentNode.removeChild(elements[0]);
    }
}

Using jQuery (which you really could be using in this case, I think), you could do this like so:

$('.column').remove();

Otherwise, you're going to need to use the parent of each element to remove it:

element.parentNode.removeChild(element);

Using ES6 you could do like:

const removeElements = (elms) => elms.forEach(el => el.remove());

// Use like:
removeElements( document.querySelectorAll(".remove") );
<p class="remove">REMOVE ME</p>
<p>KEEP ME</p>
<p class="remove">REMOVE ME</p>

In pure vanilla Javascript, without jQuery or ES6, you could do:

const elements = document.getElementsByClassName("my-class");

while (elements.length > 0) elements[0].remove();

One line

document.querySelectorAll(".remove").forEach(el => el.remove());

For example you can do in this page to remove userinfo

document.querySelectorAll(".user-info").forEach(el => el.remove());

This works for me

while (document.getElementsByClassName('my-class')[0]) {
        document.getElementsByClassName('my-class')[0].remove();
    }