The core difference between the lastChild
and lastElementChild
DOM element properties is that,
-
The
lastChild
DOM element property returns atext
,comment
, or anElement
that comes as the last in a parent element. Put simply, it returns the last thing whether it may be oftext
,comment
, or anElement
type. -
The
lastElementChild
element property, on the other hand, returns the lastElement
type as the value. Even If there aretext
orcomment
which comes after it, it doesn't return thetext
or thecomment
as the values.
Let's look at an example.
Consider this div
tag with:
span
tagtext
ofHello World!
- a
paragraph
tag - 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.