JavaScript element.attachShadow() Method

You are Here:

JavaScript element.attachShadow() Method

The element.attachShadow() method attaches a shadow DOM tree to the specified element and returns a reference to its ShadowRoot.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point">Main Element</p> <script> var x = document.getElementById("point"); var node = document.createElement("h2"); var shadowRoot = node.attachShadow({mode: "open"}); shadowRoot.innerHTML = '<div id="myShadowChild">content</div>'; var shadowChild = shadowRoot.getElementById("myShadowChild"); console.log(node.shadowRoot); </script> </body> </html>

Syntax

element.attachShadow(shadowRootInit)

Parameter Values

ValueTypeExplanation
shadowRootInitRequired{mode: "open"} - Elements of the shadow root are accessible from JavaScript outside the root.
{mode: "closed"} - Denies access to the node(s) of a closed shadow root from JavaScript outside it.

Return Values

ValueExplanation
ObjectReturns a ShadowRoot object (when mode is open).
nullReturns null (when mode is closed).

element.attachShadow() with Options

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point">Main Element</p> <script> var x = document.getElementById("point"); var node = document.createElement("h2"); var shadowRoot = node.attachShadow({mode: "closed"}); shadowRoot.innerHTML = '<div id="myShadowChild">content</div>'; var shadowChild = shadowRoot.getElementById("myShadowChild"); console.log(node.shadowRoot); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author