When developing UI using HTML and JavaScript, as it happens when using jQuery libraries (and similar), the internal implementation of the widgets we draw on screen is not encapsulated from the rest of the page. This lack of encapsulation means that whenever the page CSS or the page JavaScript change it might influence our UI. The lack of encapsulation risks future upgrades for our library that include changes in the internal details of the widgets.
The Shadow DOM specification addresses this encapsulation problem. When using the Shadow DOM, elements can get a new kind of node associated with them. This new kind of node is called a shadow root. An element that has a shadow root associated with is called a shadow host. The content of a shadow host isn’t rendered. The content of the shadow root is rendered instead.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shadow DOM Sample</title> </head> <body> <bt>Hello, world!</bt> <script> var host = document.querySelector('bt'); var root = host.createShadowRoot(); root.textContent = "שלום"; </script> </body> </html>
The following video clip shows the execution of this code sample and explains it. The use of Shadow DOM is popular in frameworks such as AngularJS.
If you try to write code in JavaScript that gets the content of the