Lightning Web Components

Understanding Shadow DOM and Template in LWC

Pinterest LinkedIn Tumblr

In this post, We will try to understand  Shadow Dom, and Template before deep diving into LWC. In the earlier post, we discussed the DOM(Document Object Model). You could click on the link(DOM) to understand more about it. Shadow Dom hides implementation details(Encapsulates) and allows it to have its own “Shadow ” DOM tree, that cannot be accessed accidentally from the main Document. Example: If we want to play an Audio or video file we will have controls to either forward the video or backward the video as well as to mute or unmute the sound etc. In order to get the below playback file/player we need to use only one line of code in the html/Javascript.

<audio controls><source src=”horse.mp3″ type=”audio/mpeg”></audio>

If you observe the code, we do not see any speaker or play related functionality. All the details are encapsulated inside a single tag <audio controls> which was implemented using Shadow DOM. When we inspect the page we do not see the details other than audio controls related functionality.

If we enable “Show user agent shadow DOM” then we would be able to see the implementation details. After enabling the setting we are able to buttons/time control under the shadow content.

Structure of shadow DOM:

An element that has a shadow root associated with it is called “shadow host”. The shadow root can be treated as an ordinary DOM element so that we can append arbitrary nodes to it.

With Shadow DOM, all markup and CSS are scoped to the host element. In other words, CSS styles defined inside a Shadow Root won’t affect its parent document, CSS styles defined outside the Shadow Root won’t affect the main page.


Write A Comment