Patrick's Forum

Shadow DOM Basics

by patricktdavies posted Jul 22 2020, 7:03

What is a Shadow DOM?

Shadow DOM’s allow you to hidden subtree’s to elements in the regular DOM tree. This means you can isolate code encapsulated inside an element, like a div, from external Java Script and CSS. Currently, Shadow DOM’s are incorporated into embedded bots, live chats, and web avatars.

To embed your own bots, live chats, or web avatars visit botlibre.biz or botlibre.com.

 

How to create a Shadow DOM

Initially you need an element to encapsulate your code. In this case thats a div called “holder”. You can attach Shadow DOM's to things like divs, spans, headers, bodies, and autonomous custom elements with valid names; Note that not all elements can have Shadow Dom’s attached.

 

var holder = document.createElement(“div”);

Let root = holder.attachShadow({mode: ‘open’});

 

The above “holder.attachShadow({mode: ‘open’});” attaches the shadow to holder.

“mode: ‘open’” returns a shadow root object which is useful dynamic changes, while “mode: ‘closed’” would return null.

 

Working with a Shadow DOM

To update the html within the holder, one option is to edit holder.innerHTML. You can also append elements created by the document as follows (utilizing holder and root from above):

 

var spanExample = document.createElement('span');

root.appendChild(spanEample);

 

Elements in the root can be accessed via root.getElementById() or created with root.createElement(). You will not be able to access elements inside the Shadow DOM via document.getElementById().

 

Browser compatibility

Shadow DOM's are compatible with nearly all modern desktop browsers, with the exception of internet explorer. They are also compatible with all major mobile browsers.

 


Id: 12004797
Posted: Jul 22 2020, 7:03
Updated: Jul 22 2020, 7:04
Replies: 0
Views: 145, today: 1, week: 1, month: 1
0 0 0.0/5