Monday, September 17, 2018

JavaScript - Document Object Model - Delete Element

Let us first explore the cross browser method of deleting elements. Consider the following body code:

<body>
  <h1 id="firstId">hey there</h1>
<ul>
  <li ><a href="#">Link 1</a></li>
  <li class = "dimple">full</li>
  <li class = "pimple">ness</li>
  </ul>
</body>


Now, if you want to remove the second list item with text = full . Then we do it in the following manner:

var a = document.querySelectorAll('li')[1];
a.parentElement.removeChild(a);

This looks somewhat inconvinient as we are first selecting the parent and then removing the child. But, this is the only method with is supported by the older browsers.

The better way would be to just call the remove method.
var a = document.querySelectorAll('li')[1];
a.remove();

But use this with caution as it does not work with all the browsers.

No comments:

Post a Comment