Brett Brett - 2 months ago 7
Javascript Question

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.

Answer

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