HTML DOM Element lastChild attribute
- Previous page lang
- Next page lastElementChild
- Go back to the previous level HTML DOM Elements Object
Definition and usage
lastChild
The attribute returns the last child node of the specified node as a Node object.
lastChild
The attribute is read-only.
Note
lastChild
It returns these child nodes: element nodes, text nodes, or comment nodes.
The blank spaces between elements are also text nodes.
Alternative solution:
lastElementChild attribute - lastElementChild
The attribute returns the last child element (ignoring text and comment nodes).
See also:
Node attributes
HTML nodes and elements
In HTML DOMIn (Document Object Model), an HTML document is a collection of nodes that have (or do not have) child nodes.
Noderefers to element nodes, text nodes, and comment nodes.
ElementThe blank spaces between them are also text nodes.
While elements are just element nodes.
Child nodes and child elements
childNodes ReturnChild nodes(element nodes, text nodes, and comment nodes).
children ReturnChild elements(instead of text and comment nodes).
firstChild and firstElementChild
firstChild Return the firstChild nodes(Element node, text node, or comment node). The spaces between elements are also text nodes.
firstElementChild Return the firstChild elements(It does not return text nodes and comment nodes).
lastChild vs. lastElementChild
lastChild Return the last oneChild nodes(Element node, text node, or comment node). The spaces between elements are also text nodes.
lastElementChild Return the last oneChild elements(It does not return text nodes and comment nodes).
Example
Example 1
Return the HTML content of the last child node of the <ul> element:
document.getElementById("myList").lastChild.innerHTML;
Example 2
Get the text of the last child node of the <select> element:
let text = document.getElementById("mySelect").lastChild.text;
Example 3
This example demonstrates the interference of spaces, try to get the node name of the last child node of "myDIV":
<div id="myDIV"> <p>Looks like first child</p> <p>Looks like last Child</p> </div> <script> let text = document.getElementById("myDIV").lastChild.nodeName; </script>
Example 4
However, if you remove the spaces from the source, there is no #text node in "myDIV":
<div id="myDIV"><p>First child</p><p>Last Child</p></div> <script> let text = document.getElementById("myDIV").lastChild.nodeName; </script>
Syntax
element.lastChild
or
node.lastChild
Return value
Type | Description |
---|---|
Node | The last child node of the node. |
null | If there are no children. |
Browser support
element.lastChild
It is a DOM Level 1 (1998) feature.
All browsers fully support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous page lang
- Next page lastElementChild
- Go back to the previous level HTML DOM Elements Object