您好,
我想从一个不会出现在DOM中的元素中获取文本,直到用户悬停另一个元素,所以我添加了一个观察者,但我仍然得到一个错误,说明TypeError:document.getElementById(...)为null。
这是我的代码:
document.addEventListener("DOMContentLoaded", function(event) {
// Select the node that will be observed for mutations
var parentOfMyList = document.body;
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
var lists = document.getElementById("list").textContent;
console.log(lists)
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
observer.observe(parentOfMyList, config);
});
我做错了什么?
谢谢。
答案 0 :(得分:0)
在尝试使用之前检查元素是否存在。
document.addEventListener("DOMContentLoaded", function(event) {
// Select the node that will be observed for mutations
var parentOfMyList = document.body;
// Options for the observer (which mutations to observe)
var config = {
attributes: true,
childList: true,
subtree: true
};
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
var elt = document.getElementById("list");
if (elt) {
var lists = elt.textContent;
alert(lists);
}
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
observer.observe(parentOfMyList, config);
var container = document.querySelector("#container");
document.querySelector("#b1").addEventListener("click", function() {
var l = document.createElement("div");
l.id = "list";
l.textContent = "This is the list";
container.appendChild(l);
});
document.querySelector("#b2").addEventListener("click", function() {
var l = document.createElement("div");
l.id = "list2";
l.textContent = "This is list #2";
container.appendChild(l);
});
});
#container {
height: 50px;
width: 100%;
background-color: yellow;
}
#list1 {
background-color: green;
}
#list2 {
background-color: pink;
}
<div id="container"></div>
<button id="b1">Click to create list</button>
<br>
<button id="b2">Click to create list2</button>