How to Use the lastElementChild Property in JavaScript?

Estimated read time 1 min read

The lastElementChild property in JavaScript is used to access the last child element of a given node in the DOM (Document Object Model). Here’s how you can use it:

  1. Select the parent node: To access the lastElementChild property, you need to first select the parent node. You can use various methods to do this, such as document.getElementById(), document.querySelector(), etc.
  2. Access the property: Once you have the parent node, you can access the lastElementChild property. For example:
let parentNode = document.getElementById("parentId");
let lastChild = parentNode.lastElementChild;
  1. Use the property: After you have the last child element, you can use it in various ways, such as changing its styles, modifying its content, etc.

Here’s an example that demonstrates how to change the background color of the last child element:

let parentNode = document.getElementById("parentId");
let lastChild = parentNode.lastElementChild;
lastChild.style.backgroundColor = "yellow";

Note that the lastElementChild property only returns the last child element node, and not any text nodes or comments that may be present.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply