Remove all child elements of a DOM node in JavaScript

前端 未结 30 1314
花落未央
花落未央 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:12

    var myNode = document.getElementById("foo");
    var fc = myNode.firstChild;
    
    while( fc ) {
        myNode.removeChild( fc );
        fc = myNode.firstChild;
    }
    

    If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.

    $('#foo').empty();
    

    The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up.

    If you simply use DOM methods of removing the children, that data will remain.

提交回复
热议问题