使用观察者检测何时出现元素



hi,

我想从dom中不会出现的元素中获取文本,直到用户徘徊在另一个元素上,所以我添加了一个观察者,但我仍然会遇到一个错误,说typeError:documenterror: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);   
});

我在做什么错?

谢谢。

在尝试使用之前检查该元素是否存在。

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>

最新更新