The core difference between the lastChild and lastElementChild DOM element properties is that,
-
The
lastChildDOM element property returns atext,comment, or anElementthat comes as the last in a parent element. Put simply, it returns the last thing whether it may be oftext,comment, or anElementtype. -
The
lastElementChildelement property, on the other hand, returns the lastElementtype as the value. Even If there aretextorcommentwhich comes after it, it doesn't return thetextor thecommentas the values.
Let's look at an example.
Consider this div tag with:
spantagtextofHello World!- a
paragraphtag - another text of
Hai, I'm another simple text
inside it as its children.
<div>
<span>I'm inside a SPAN tag</span>
Hello World!
<p>I'm a paragraph</p>
Hai, I'm another simple text.
</div>
Now let's use the lastChild and the lastElementChild DOM element properties on the div element to check what it returns.
// get reference to the div tag
const div = document.querySelector("div");
// lastChild DOM element property
const lastChild = div.lastChild;
// lastElementChild DOM element property
const lastElementChild = div.lastElementChild;
console.log(lastChild); // Hai, I'm another simple text.
console.log(lastElementChild); // <p>I'm a paragraph</p>
As you can see the lastChild returns the last text content Hai, I'm another simple text and the lastElementChild returns the last element i.e para tag (<p>I'm a paragraph</p>).
See this example live in JSBin.