Introduction to Shadow DOM

Since the launch of HTML5, many and many things are being added to make it more useful and efficient. One such thing is the shadow DOM. Most of you must be knowing what DOM is. So you must be thinking what shadow DOM actually is.

Straightforward, it is encapsulation in HTML. You can create your own custom tags which can then be directly used by users in their webpages. For example, let’s take the <video> tag. But to explore the tag first you must ensure that the “Show Shadow DOM” checkbox is selected in the web browser developer console’s settings panel. Once you have done (which I assume you have did) just inspect the video element. And there you will find some elements you didn’t know about.

That’s nothing but shadow DOM. Those tags inside are hidden from you but still you can use them. That’s how browser makers implement their own tags. Even you can make custom tags which you can use anywhere you want. The node that contains all of your shadow DOM is called the Shadow Host. The first child inside the shadow host is called the shadow root and everything inside the shadow root is covered by a shadow boundary.

Creating a shadow DOM is pretty straightforward. Every element has a method called createShadowRoot().
For example, we have a <div> tag with the text “Hello World” inside it and we give the <div> tag a class of widget. Like <div class="widget">Hello World</div>

Then in the JavaScript part we just have to write the following:

var host = document.querySelector(".widget");
var root = host.createShadowRoot();
root.innerHTML = "<em>I'm the shadow element!</em>"

What I did here was that I just called the createShadowRoot() method on the host object, which here was the <div> tag, and then I added an emphasized string inside of it by using the innerHTML property. Now, if you try this out, you will notice that when the script runs it replaces the inner text of “Hello World” by “I’m the shadow element!”. You would think where did the “Hello World” go. It didn’t go anywhere; it was there all the time. Only the thing is that the original content was not rendered, instead the shadow element was rendered.

Only descendants of the shadow root are rendered.

That was a basic introduction on shadow DOM. I hope you liked it.

Advertisements

2 thoughts on “Introduction to Shadow DOM

Your Thoughts -

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s