[英]How to querySelectorAll elements added to the DOM with javascript?
I am developing a chat app, and my issue raises when I try to add new elements to a list of chat rooms, see them, and interact with them without reloading the page.我正在开发一个聊天应用程序,当我尝试将新元素添加到聊天室列表、查看它们并与它们交互而不重新加载页面时,我的问题就出现了。
I am adding HTML elements to a list with JavaScript.我将 HTML 元素添加到具有 JavaScript 的列表中。
Then I try to querySelectorAll elements in the list.然后我尝试查询列表中的SelectorAll 元素。
The elements that were loaded from the server on page load can be selected.可以选择在页面加载时从服务器加载的元素。
But the newly created elements with JavaScript don't seem to get selected.但是新创建的带有 JavaScript 的元素似乎没有被选中。
Here is how I try to select my elements and, when clicked, execute some code for each of them:这是我如何尝试 select 我的元素,并在单击时为每个元素执行一些代码:
document.querySelectorAll('.select-room').forEach(p => {
p.onclick = () => { <my code here> })
The elements that are already on the list get selected just fine and my code executes alright.已经在列表中的元素被选中就好了,我的代码执行得很好。
But when I add a new element with JavaScript.但是当我用 JavaScript 添加一个新元素时。 Even though the HTML of it looks just the same as the HTML of other existing elements, including the class by which it gets selected, the result is I can only select those after reloading the page.
Even though the HTML of it looks just the same as the HTML of other existing elements, including the class by which it gets selected, the result is I can only select those after reloading the page.
Is there a way I can listen for changes made to the DOM, so that after adding with JavaScript new elements with the same class, they will be selected like the others without having to reload the page?有没有办法我可以监听对 DOM 所做的更改,以便在使用 JavaScript 添加具有相同 class 的新元素后,它们将像其他元素一样被选中,而无需重新加载页面?
Here is a Minimal, Complete, Reproducible Example of my problem:这是我的问题的最小,完整,可重现的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mcr problem</title>
<script>
document.addEventListener("DOMContentLoaded", () => {
// Clicking element in the list shows an alert.
document.querySelectorAll(".clickable").forEach(li => {
li.onclick = () => {alert("interaction!")};
});
// Clicking on button adds new element to the list
document.querySelector("#add-btn").onclick = () => {
newLi = document.createElement("li");
newLi.classList.add("clickable");
newLi.innerHTML = "New Item";
document.querySelector("#parent-list").append(newLi);
};
});
</script>
</head>
<body>
<h1>List of items</h1>
<button id="add-btn">Add</button>
<ul id="parent-list">
<li class="clickable" id="post-1">Item 1</li>
<li class="clickable" id="post-2">Item 2</li>
<li class="clickable" id="post-3">Item 3</li>
</ul>
</body>
</html>
Reasons why alert was not getting called DOMContentLoaded
未调用
DOMContentLoaded
警报的原因
This event triggers when the DOM tree forms ie the script is loading.此事件在 DOM 树 forms 即脚本正在加载时触发。 Scripts start to run before all the resources like images, CSS, and JavaScript loads.
脚本在图像、CSS 和 JavaScript 等所有资源加载之前开始运行。 You can attach this event either to the window or the document objects
您可以将此事件附加到 window 或文档对象
and at that time the query selector has only 3 node of class .clickable
so it apply only on those 3 elements.并且当时查询选择器只有 class
.clickable
的 3 个节点,因此它仅适用于这 3 个元素。
In javascript DOMNodeInserted
在 javascript
DOMNodeInserted
It fires when the script inserts a new node in the DOM tree using appendChild(), replaceChild(), insertBefore(), etc.当脚本使用 appendChild()、replaceChild()、insertBefore() 等在 DOM 树中插入新节点时,它会触发。
document.addEventListener("DOMContentLoaded", () => { document.querySelectorAll(".clickable").forEach((li) => { li.onclick = () => commonAlertMethod(); }); // Clicking on button adds new elemnt to the list document.querySelector("#add-btn").onclick = () => { newLi = document.createElement("li"); newLi.classList.add("clickable"); newLi.innerHTML = "New Item"; document.querySelector("#parent-list").append(newLi); }; }); document.addEventListener("DOMNodeInserted", () => { // Clicking element in the list shows an alert. document.querySelectorAll(".clickable").forEach((li) => { li.onclick = () => commonAlertMethod(); }); }); function commonAlertMethod() { alert("interaction;"); }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1>List of items</h1> <button id="add-btn">Add</button> <ul id="parent-list"> <li class="clickable" id="post-1">Item 1</li> <li class="clickable" id="post-2">Item 2</li> <li class="clickable" id="post-3">Item 3</li> </ul> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.