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.

100 thoughts on “Removing elements by class name?”

Leave a Comment