简体   繁体   中英

Unable to attach event to an element in contextual fragment

I tried to attach an event to an element in a contextual fragment and then appended this element to body. But the event doesn't get attached.

var range = document.createRange();
var listE1 = "<div>Hello World</div>"
range.selectNode(document.getElementsByTagName("div").item(0));
var element = range.createContextualFragment(listEl);

element.querySelector("div").addEventListener("click", function () {
    alert("hello");
}, true);

document.body.appendChild(element);

After appending this element to body, the div doesn't have any event at all

I stumbled upon here after looking for the same answer and I know this is a very old question hope this helps or points to a better direction.

The range.createContextualFragment(listEl); returns a DocumentFragment . In a nutshell a DocumentFragment is minimalized DOM object. It doesn't have an attachEventListener.

If you want you can either use DOMParser or use document.createElement

Here's an example of how you can use DOMParser

let listE1 = "<div>Hello World</div>"
let element = new DOMParser().parseFromString(listE1 , 'text/html').documentElement;
element.addEventListener("click", function () {
    alert("hello");
}, true);

document.body.appendChild(element);

Hope this helps.

only a lot of little mistake, the code should run right easy: we should add the fragment to document, then add the event listener

 var range = document.createRange(); var listE1 = "<div id='hello'>Hello World</div>" range.selectNode(document.getElementsByTagName("div").item(0)); var element = range.createContextualFragment(listE1); // listel -> liste1 document.body.appendChild(element); // should add to document first document.querySelector("div#hello").addEventListener("click", function() { // element->document alert("hello"); }, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM