Removing elements by class name?

后端 未结 16 1617
猫巷女王i
猫巷女王i 2020-11-27 12:06

I have the below code to find elements with their class name:

// Get the element by their class name
var cur_columns = document.getElementsByClassName(\'colu         


        
相关标签:
16条回答
  • 2020-11-27 12:55

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

    const elements = document.getElementsByClassName("my-class");
    
    while (elements.length > 0) elements[0].remove();
    
    0 讨论(0)
  • 2020-11-27 12:57

    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());
    
    0 讨论(0)
  • 2020-11-27 12:58

    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>

    0 讨论(0)
  • 2020-11-27 12:58

    Yes, you have to remove from the parent:

    cur_columns[i].parentNode.removeChild(cur_columns[i]);
    
    0 讨论(0)
提交回复
热议问题