Skip to content

Get Child Elements in Lightning Web Components

Hello folks,

Here, I am gonna talk about two methods of Element class which are used to get the child elements : 

  1. Element.getElementsByTagName()
  2. Element.getElementsByClassName() 

And the good news is that now we can use them in the Lightning Web Components according to the Summer’20 release.

Let’s talk more about them now.

Element.getElementsByTagName() – returns a collection of an elements’s child elements with the specified tag name. All descendants of the specified element are searched, but not the element itself.
Element.getElementsByClassName() –  returns a collection of an element’s child elements with the specified class name.

In the below example,
Firstly, I am getting the child element “lightning-input” of the parent element “div” by using getElementsByClassName() and then binding the value.
Secondly, I am getting the child elements “li” of the parent element “ul” by using the getElementsByTagName() and then dynamically changing the background-color.

<template>
    <lightning-card>
        <div class="slds-p-around_small">
            <lightning-input label="Enter Color" value={value} onchange={handleChange} class="fun"></lightning-input>
        </div>

        <ul class="slds-p-left_large">
            <li>Element.getElementsByTagName()</li>
            <li>Element.getElementsByClassName()</li>
        </ul>
    </lightning-card>
</template>
import { LightningElement, track } from 'lwc';

export default class GetChildElements extends LightningElement {
    @track value;

    handleChange(event) {
        let parentTag = this.template.querySelector('div');
        let childElements = parentTag.getElementsByClassName('fun');

        let parentUl = this.template.querySelector('ul');
        let childListElements = parentUl.getElementsByTagName('li');

        // Bind the value
        this.value = childElements[0].value;

        // Add style dynamically
        childListElements.forEach(element => {
            element.style = `background-color: ${this.value};`;
        });

    }
} 
li {
    list-style-type: disc;
}

Let’s see the output.

Stay safe!!

Published inCoding Mania

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *