Failed to execute removeChild on Node

后端 未结 5 1714
盖世英雄少女心
盖世英雄少女心 2021-02-02 06:22

Other stack answers such as this and this seem to be specialized cases and I believe my case is more generalized. I am doing this in my js:

var markerDiv = docum         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 06:58

    Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

    You'd want to remove that wrapper div, or not add it at all.

    Here's the "not adding it at all" option:

    var markerDiv = document.createElement("div");
    markerDiv.innerHTML = "
    123
    "; document.getElementById("playerContainer").appendChild(markerDiv.firstChild); // -------------------------------------------------------------^^^^^^^^^^^ setTimeout(function(){ var myCoolDiv = document.getElementById("MyCoolDiv"); document.getElementById("playerContainer").removeChild(myCoolDiv); }, 1500);

    Or without using the wrapper (although it's quite handy for parsing that HTML):

    var myCoolDiv = document.createElement("div");
    // Don't reall need this: myCoolDiv.id = "MyCoolDiv";
    myCoolDiv.style.color = "#2b0808";
    myCoolDiv.appendChild(
      document.createTextNode("123")
    );
    document.getElementById("playerContainer").appendChild(myCoolDiv);
    
    setTimeout(function(){ 
        // No need for this, we already have it from the above:
        // var myCoolDiv = document.getElementById("MyCoolDiv");
        document.getElementById("playerContainer").removeChild(myCoolDiv);
    }, 1500);

提交回复
热议问题