Shadow DOM in HTML5

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 element it won’t be the text in hebrew. It will be the text written in between the elements in the HTML file.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences