HTML - DOM lastChild Property



The HTML DOM lastChild property is used to access and retrieve the last child node of a specified parent element within the HTML DOM.

This property is useful for manipulating the DOM, as it allows developers to easily identify and interact with the last child, whether it is an element node, text node, or comment.

If the parent element has no children, lastChild will return null.

Syntax

Following is the syntax of HTML DOM lastChild property −

element.lastChild;

Parameters

Since it is a property, it does not accept any parameters.

Return Value

This property returns a node that points to the last child node of a specific parent element. If no last child exists, it returns 'null'.

Example 1: Accessing the lastChild of Div Element

The following is the basic example of the HTML DOM lastChild property. It retrieved the last child of a

element −




HTML DOM lastChild


First Span element
Second div

Last paragraph

Click the below button to get the last child of div element.

The above program returns the last child of a "div" element.

Example 2: Last Child Node of an "ul" Element

Following is another example of the HTML DOM lastChild element. We use this property to access the last child of the

    element −

    
    
    
    HTML DOM lastChild
    
    
    
    

    Below are List of ul items :

    • HTML
    • CSS
    • JavaScript
    • DSA

    Example 3: Modifying Last Child Content of Div Element

    This example shows how to dynamically modify the content of the last child of a

    element using the lastChild Property −

    
    
    
    HTML DOM lastChild
    
    
    

    This is the div content with their child nodes:

    First paragraph

    Second div
    Span element

    Last paragraph

    Modified last child node:

    Example 4: Inserting Last Child Dynamically

    The example below shows the dynamic insertion of a new last child element into a list of items upon clicking a button using the lastChild property −

    
    
     
    HTML DOM lastChild
    
    
    
    

    Inserting a new Last Child dynamically..

    First paragraph

    • Item 1
    • Item 2
    • Item 3
    Span element

    Last paragraph with some whitespace before closing tag

    Supported Browsers

    Property Chrome Edge Firefox Safari Opera
    lastChild Yes Yes Yes Yes Yes
    html_dom.htm
    Advertisements