javascript tutorial - [Solved-5 Solutions] Remove element by id - javascript - java script - javascript array



Problem:

How to remove element by id ?

Solution 1:

must go to its parent first:

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

Crossbrowser:

var element = document.getElementById("element-id");
element.outerHTML = "";
delete element;
click below button to copy the code. By JavaScript tutorial team

Solution 4:

function remove(id) {
    var elem = document.getElementById(id);
    return elem.parentNode.removeChild(elem);
}
click below button to copy the code. By JavaScript tutorial team

remove function

Solution 5:

element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the the parent node, then remove the reference to the child node.


Related Searches to javascript tutorial - Remove element by id