Removing elements by class name?

I have the below code to find elements with their class name:

// Get the element by their class name
var cur_columns = document.getElementsByClassName('column');

// Now remove them

for (var i = 0; i < cur_columns.length; i++) {

}

I just don't know how to remove them..... do I HAVE to reference the parent or something? What's the best way to handle this?

@Karim79:

Here is the JS:

var col_wrapper = document.getElementById("columns").getElementsByTagName("div");
var len = col_wrapper.length;

alert(len);

for (var i = 0; i < len; i++) {
    if (col_wrapper[i].className.toLowerCase() == "column") {
        col_wrapper[i].parentNode.removeChild(col_wrapper[i]);
    }
}

Here is the HTML:

<div class="columns" id="columns">
    <div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
    <div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
    <div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
    <div class="column"><input type="checkbox" name="col_list[]" value="cows">cows</div>
    <div name="columnClear" class="contentClear" id="columnClear"></div>
</div>

Edit: Well ended up just using the jQuery option.


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

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

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

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

Use Element.remove()

Remove single element

document.querySelector("#remove").remove();

Remove multiple elements

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

If you want a handy reusable function:

const remove = (sel) => document.querySelectorAll(sel).forEach(el => el.remove());

// Use like:
remove(".remove");
remove("#remove-me");
<p class="remove">REMOVE ME</p>
<p>KEEP ME</p>
<p class="remove">REMOVE ME</p>
<p id="remove-me">REMOVE ME</p>

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