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:
- 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 asdocument.getElementById()
,document.querySelector()
, etc. - 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;
- 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.
+ There are no comments
Add yours