Removing elements by class name?

后端 未结 16 1615
猫巷女王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:35

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

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

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

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

    This works for me

    while (document.getElementsByClassName('my-class')[0]) {
            document.getElementsByClassName('my-class')[0].remove();
        }
    
    0 讨论(0)
  • 2020-11-27 12:44
    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();
    
    
    0 讨论(0)
提交回复
热议问题