212

I have the code below 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++) {
      
}

Do I have to reference the parent or something? What's the best way to handle this?

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>
0

17 Answers 17

284

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]);
    }
}
3
  • 24
    If anyone is wondering why he's removing the first element (index 0) always, it's because when you remove an element, it also shrinks the elements array. Commented Jul 27, 2017 at 16:35
  • what about the others indexes (accept the 0 index)?
    – ofir_aghai
    Commented Aug 2, 2017 at 8:28
  • 2
    @ofir_aghai as @JeffersonLima points the getElementsByClassName is a live collection. developer.mozilla.org/en-US/docs/Web/API/NodeList Commented Aug 7, 2017 at 7:21
241

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

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>

0
61

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

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

while (elements.length > 0) elements[0].remove();
1
  • This one work on WordPress using Elementor page builder and adding a HTML element to add JavaScript without having to pay for the Pro version
    – Maduro
    Commented Oct 4, 2020 at 1:25
34

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

This works for me

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

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.

0
5

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.

3

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

Yes, you have to remove from the parent:

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

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

You can use this syntax: node.parentNode

For example:

someNode = document.getElementById("someId");
someNode.parentNode.removeChild(someNode);
1
  • 7
    This question asked to remove by className
    – JoeTidee
    Commented Jul 23, 2017 at 12:18
1

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

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>

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

-1

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

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

1
  • 1
    This will not work since the array of the loop is modified inside the loop itself. The result is that the last element will be skipped.
    – Franc
    Commented Oct 2, 2016 at 13:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.