Removing elements by class name?

JavascriptRemoveclass

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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>

Solution 4 - Javascript

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

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

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

Solution 5 - Javascript

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

Solution 6 - Javascript

This works for me

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

Yes, you have to remove from the parent:

cur_columns[i].parentNode.removeChild(cur_columns[i]);

Solution 12 - Javascript

You can use this syntax: node.parentNode

For example:

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

Solution 13 - Javascript

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

Solution 14 - Javascript

This is how I've completed a similar task in Pure JavaScript.

function setup(item){
   document.querySelectorAll(".column") /* find all classes named column */
  .forEach((item) => { item /* loop  through each item */
      .addEventListener("click", (event) => { item
        /* add event listener for each item found */
          .remove(); /* remove self - changed node as needed */
      });
  });

}

setup();

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrettView Question on Stackoverflow
Solution 1 - JavascriptVeikko KarsikkoView Answer on Stackoverflow
Solution 2 - JavascriptLior CohenView Answer on Stackoverflow
Solution 3 - JavascriptRoko C. BuljanView Answer on Stackoverflow
Solution 4 - JavascripttocquevilleView Answer on Stackoverflow
Solution 5 - JavascriptMohsenView Answer on Stackoverflow
Solution 6 - JavascriptУляна РізникView Answer on Stackoverflow
Solution 7 - Javascriptkarim79View Answer on Stackoverflow
Solution 8 - JavascriptAlexanderView Answer on Stackoverflow
Solution 9 - JavascriptWolfgang LeonView Answer on Stackoverflow
Solution 10 - JavascriptlchachurskiView Answer on Stackoverflow
Solution 11 - JavascriptDavid TangView Answer on Stackoverflow
Solution 12 - JavascriptComputerishView Answer on Stackoverflow
Solution 13 - JavascriptCan PERKView Answer on Stackoverflow
Solution 14 - JavascriptZStoneDPMView Answer on Stackoverflow
Solution 15 - JavascriptFatih ErtuğralView Answer on Stackoverflow
Solution 16 - Javascriptshao.loView Answer on Stackoverflow
Solution 17 - JavascriptGustavo RuizView Answer on Stackoverflow