JavaScript DOM remove element

后端 未结 4 1767
猫巷女王i
猫巷女王i 2020-11-22 11:18

I\'m trying to test if a DOM element exists, and if it does exist delete it, and if it doesn\'t exist create it.

var duskdawnkey = localStorage[\"duskdawnkey         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 11:50

    Using Node.removeChild() does the job for you, simply use something like this:

    var leftSection = document.getElementById('left-section');
    leftSection.parentNode.removeChild(leftSection);
    

    In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

    The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

    But you can use remove method if you using jQuery...

    $('#left-section').remove(); //using remove method in jQuery
    

    Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

提交回复
热议问题