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.

Answers:

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

If you prefer not to use JQuery:

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

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>

Answer

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

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

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

This works for me

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

Brett - are you aware that getElementyByClassName support from IE 5.5 to 8 is not there according to quirksmode?. You would be better off following this pattern if you care about cross-browser compatibility:

  • Get container element by ID.
  • Get needed child elements by tag name.
  • Iterate over children, test for matching className property.
  • elements[i].parentNode.removeChild(elements[i]) like the other guys said.

Quick example:

var cells = document.getElementById("myTable").getElementsByTagName("td");
var len = cells.length;
for(var i = 0; i < len; i++) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
    }
}

Here's a quick demo.

EDIT: Here is the fixed version, specific to your markup:

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

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

The problem was my fault; when you remove an element from the resulting array of elements, the length changes, so one element gets skipped at each iteration. The solution is to store a reference to each element in a temporary array, then subsequently loop over those, removing each one from the DOM.

Try it here.

Answer

I prefer using forEach over for/while looping. In order to use it's necessary to convert HTMLCollection to Array first:

Array.from(document.getElementsByClassName("post-text"))
    .forEach(element => element.remove());

Pay attention, it's not necessary the most efficient way. Just much more elegant for me.

Answer

Yes, you have to remove from the parent:

cur_columns[i].parentNode.removeChild(cur_columns[i]);
Answer
const elem= document.getElementsByClassName('column')

for (let i = elem.length; 0 < i ; )
    elem[--i].remove();

OR

const elem= document.getElementsByClassName('column')

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

Answer

It's very simple, one-liner, using ES6 spread operator due document.getElementByClassName returns a HTML collection.

[...document.getElementsByClassName('dz-preview')].map(thumb => thumb.remove());
Answer

The skipping elements bug in this (code from above)

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

can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)

var len = cells.length;
for(var i = len-1; i >-1; i--) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
   }
}
Answer

You can you use a simple solution, just change the class, the HTML Collection filter is updated:

var cur_columns = document.getElementsByClassName('column');

for (i in cur_columns) {
   cur_columns[i].className = '';
}

Ref: http://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html

Answer

You can use this syntax: node.parentNode

For example:

someNode = document.getElementById("someId");
someNode.parentNode.removeChild(someNode);
Answer

Recursive function might solve your problem like below

removeAllByClassName = function (className) {
    function findToRemove() {
        var sets = document.getElementsByClassName(className);
        if (sets.length > 0) {
            sets[0].remove();
            findToRemove();
        }
    }
    findToRemove();
};
//
removeAllByClassName();
Answer

In case you want to remove elements which are added dynamically try this:

document.body.addEventListener('DOMSubtreeModified', function(event) {
    const elements = document.getElementsByClassName('your-class-name');
    while (elements.length > 0) elements[0].remove();
});
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.