简体   繁体   中英

How to add event to element created with js?

I created the script below. It puts the body in a div, as desired. However, the event handler fails. I'm sure it's a simple error.

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "</div>";
document.body.innerHTML = new_html;
document.body.getElementById("realBody").addEventListener("mouseover", function(event) {alert('body');});

How to make the event work? (Feel free to rewrite the whole thing if there's a better (simpler) way.

Edit: This works, some comments say it's the wrong way to put the body into a div, but i see no problems:

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "</div>";
document.body.innerHTML = new_html;
document.getElementById("realBody").addEventListener("mouseenter", function(event) {alert('body');});

thx!

You should attach event listener like,

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "I am border</div>";
document.body.innerHTML = new_html;
document.getElementById("realBody").addEventListener("mouseover", function (event) {
    alert('body');
});

DEMO

您需要将document.body.getElementById()更改为document.getElementById()

document.getElementById("realBody").addEventListener("mouseover", function(event) {alert('body');});

The error you're receiving is probably because of this line:

document.body.getElementById("realBody").addEventListener("mouseover", function (event) { alert('body'); });

you need to modify it to this:

document.getElementById("realBody").addEventListener("mouseover", function (event) { alert('body'); });

document.body.getElementById() just needs to be document.getElementByid()

A more proper way to add elements to the DOM would be to do something like below:

var divEl = document.createElement("div");
divEl.id = "realBody";
var textNode = document.createTextNode("Hover over me");
divEl.appendChild(textNode);
document.body.appendChild(divEl);

divEl.onmouseover = function (event) {
    alert('body');
}

As everybody explained, you need to call the getElementById() on the document object, not in an element.

But your code will loose any event handlers attached to the elements prior to your code execution as you are clearing the html and creating a new dom structure you overwritting the innerHTML.

Instead just move the existing dom to the new element like

var wrapper = document.createElement('div');
wrapper.id = 'realBody';
while (document.body.firstChild) {
    wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
wrapper.addEventListener("mouseover", function (event) {
    console.log('body');
});

Demo: Fiddle

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