To access elements rendered by component we need to use template property.
Access element from tag. <h1>Element Inside H1 Tag </h1>
const h1Element = this.template.querySelector('h1');
const h1Element = this.template.querySelector('h1');
Console.log(h1Element.innerText ); // It will print "Element Inside H1 Tag"
We can apply style sheet after getting DOM element dynamically.
h1Element.style = 'color:red;border-style: solid;'
Accessing element using class.
const userElements = this.template.querySelectorAll('.name');
It will return node list (multiple items that is why querySelectorAll is being used.)
We can set attributes to each element of node list dynamically or apply style sheet.
Array.from(userElements).forEach(item=>{
console.log(item.innerText);
item.setAttribute('title',item.innerText);
item.style = 'background-color: black;'
})
Note - Dont use Id selector with query selector in LWC
What is the use of lwc:dom = 'manul'
When we want to append html element dynamically to an element from JavaScript at that time lwc:dom directive required. it just tell LWC engine that html element going to added dynamically.
<div class="childElement" lwc:dom="manual"> </div>
const childELement = this.template.querySelector('.childElement')
childELement.innerHTML = '<p>I am a Child DOM</p>';
No comments:
Post a Comment