Remove all child elements of a DOM node in JavaScript

前端 未结 30 1394
花落未央
花落未央 2020-11-22 03:28

How would I go about removing all of the child elements of a DOM node in JavaScript?

Say I have the following (ugly) HTML:

&

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 04:10

    Ecma6 makes it easy and compact

    myNode.querySelectorAll('*').forEach( n => n.remove() );
    

    This answers the question, and removes “all child nodes”.

    If there are text nodes belonging to myNode they can’t be selected with CSS selectors, in this case we’ve to apply (also):

    myNode.textContent = '';
    

    Actually the last one could be the fastest and more effective/efficient solution.

    .textContent is more efficient than .innerText and .innerHTML, see: MDN

提交回复
热议问题