- :host and ::shadow pseudo selector can be used to style the HTML element inside shadow root.
- A shadow root can be created using createShadowRoot() method.
- In this demo, “We will create a custom element and style the HTML present inside shadow DOM”.
- A custom element can be referred in 2 ways.Inside its template it can be targeted using :host pseudo selector and from outside(document) using custom element name with ::shadow selector(customElmentName::shadow).
- Below code creates a custom element error-message and shows the 2 different way to style the inner HTML element H1 present inside shadow root.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Developing and styling shadow elements</title> <style> error-message::shadow h1{ color:red; } </style> <template id="errorTemplate"> <style> :host h1{ font-style:italic; } </style> <h1> Error Occured </h1> </template> <script> var objectPrototype = Object.create(HTMLElement.prototype); objectPrototype.createdCallback=function(){ var shadow = this.createShadowRoot(), templateContent = document.querySelector('#errorTemplate').content, templateNodes = document.importNode(templateContent, true); shadow.appendChild(templateNodes); }; var myNameElement = document.registerElement("error-message",{ prototype:objectPrototype }); </script> </head> <body> <error-message> </error-message> </body> </html>
- The output of the above code is embedded in below JSBIN link.