How to remove all elements of a certain class from the DOM?

后端 未结 4 786
有刺的猬
有刺的猬 2020-11-29 06:34



        
4条回答
  •  旧巷少年郎
    2020-11-29 06:50

    Simple ES6 answer:

    document.querySelectorAll('.classname').forEach(e => e.remove());
    

    Explanation:

    1. document.querySelectorAll() loops through the elements in the document returning a NodeList of all elements with the specified selector (e.g. '.class', '#id', 'button')
    2. forEach() loops through the NodeList and executes the specified action for each element
    3. e => e.remove() removes the element from the DOM

    Note, however, that this solution is not supported by Internet Explorer. Then again, nothing is.

提交回复
热议问题