Working with nodes in JavaScript

As you know, tags can contain other tags or, in JavaScript terms, DOM elements can contain other DOM elements. In addition, however, they may contain comments and plain text. Comments, texts and DOM elements are united by one name - nodes.

You already know the properties firstElementChild, lastElementChild, nextElementSibling, previousElementSibling. These properties only work with DOM elements, ignoring other nodes. As a rule, this is exactly what we need.

However, there are also properties firstChild, lastChild, nextSibling, previousSibling. These properties work in a similar way, however, considering all nodes. Let's see the difference between these properties with an example. Suppose we have a div containing three nodes:

<div id="elem"><!--сomm-->text<span>tag</span></div>

Get a reference to this div into a variable:

let elem = document.querySelector('#elem');

Now let's see what is contained in the properties firstChild and firstElementChild:

console.log(elem.firstChild); // comment console.log(elem.firstElementChild); // span tag

Write code that shows the difference between lastChild and lastElementChild.

Write code that shows the difference between nextSibling and nextElementSibling.

Write code that shows the difference between previousSibling and previousElementSibling.