Tuesday, September 18, 2018

JavaScript - Document Object Model - Elements and Nodes

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, instead of the following:

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

we can also use:

var a = document.querySelectorAll("li")[1];
a.parentNode.removeChild(a);

In both cases the second list item is removed. Now, when we open in developer tools of chrome. We can see that in the Elements tab - there are numerous nodes. Now, all elements are nodes. But the DOM also contains nodes which are not HTML elements. Hence, we cannot use parentElement and parentNode interchangeably all the time. But, if you are using elements in an HTML then parentElement is the one which we need to use.


No comments:

Post a Comment