Web components, add a Shadow DOM event?

I have three pages. The first is the index page, the second is the component for the index. Thirdly, it is a component for the second page.

The main code is below: Main.html:

<link class="abc" rel="import" tag="linkHtml" href="child.html />
<say-hi name="aaaa"></say-hi>
<shadow-element>
<span>(I'm in the light span dom)</span>
<div>(I'm in the light div dom)</div>
</shadow-element>

child.html:

<template id="t1">
....
<my-search value="Search"></my-search>
<content select="div"></content>
</template>

Sub-child.html:

<template id="t2">
Search:<input type="text" id="txt1" />
<input type="button" id="btn1" value="Search" />
<template id="t2">

<script>
//mainDoc
var importDoc_sub = document.currentScript.ownerDocument;

var proto3 = Object.create(HTMLElement.prototype);

proto3.createdCallback = function(){

    var template = importDoc_sub.querySelector("#t2");

    var clone = document.importNode(template.content,true);

    var root = this.createShadowRoot();
    root.appendChild(clone);
}

document.registerElement("my-search",{prototype:proto3});

//it can not register click event for btn1 button
document.addEventListener("click",function(e){
    console.log(e.target.id);
},false);

//how to add event for the btn1
//todo

The question is how to add an event for btn1 in the Shadow DOM.

+4
source share
1 answer

You can query the ShadowRoot.querySelector element. So the answer should be:

root.querySelector('#btn1').addEventListener("click", ....);

Note: I received a direct letter about this issue from the poster because the poster found my name in the Shadow DOM specification. So I answer here.

+1
source

All Articles