[英]How can I get a xhtml element by it's ID?
I am trying to get the xhtml element ID in javascript to change an element color when I click a button.我正在尝试获取 javascript 中的 xhtml 元素 ID,以在单击按钮时更改元素颜色。 I expect the browser to find an element added via an function other than
querySelector
and getElementById
.我希望浏览器能够找到通过 function 添加的元素,而不是
querySelector
和getElementById
。
As a alternative to the dom default methods, I wrote this function to find element from the nodes tree.作为 dom 默认方法的替代方法,我编写了这个 function 从节点树中查找元素。 I it didn't worked because I used the wrong NodeFilters.
我没有用,因为我使用了错误的 NodeFilters。
function findById(id) {
const treewalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_ATTRIBUTE
| NodeFilter.SHOW_TEXT, { acceptNode: function (node) {
return NodeFilter.FILTER_ACCEPT;
} }, false);
let node;
let nodes = [];
while (node = treewalker.nextNode())
nodes.push(node);
return nodes.filter(node => node.id === id);
}
Here is a minimum reproductable example of what I am trying to do.这是我正在尝试做的最小可复制示例。
/* Display the foobar text (cannot be directly written in the html file) */ let foobar = document.createElement('p'); foobar.innerHTML = 'Foo bar'; foobar.id = 'foobar'; // foobar.setAttributeNS(null, 'id', 'foobar'); document.body.appendChild(foobar); function findById(id) { const treewalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_ATTRIBUTE | NodeFilter.SHOW_TEXT, { acceptNode: function (node) { return NodeFilter.FILTER_ACCEPT; } }); let node; let nodes = []; while (node = treewalker.nextNode()) nodes.push(node); return nodes.filter(node => node.id === id); } function displayFoobar() { let e = findById('foobar'); setTimeout(function () { e.style.color = 'blue'; }, 1000); setTimeout(function () { e.style.color = 'black'; }, 2000); }
<html> <head> <title>Test</title> </head> <body> <h1>Foo bar app</h1> <button onclick="displayFoobar();">display foobar</button> </body> </html>
Your code with document.getElementById
working:您使用
document.getElementById
工作的代码:
/* Display the foobar text (cannot be directly written in the html file) */ let foobar = document.createElement('p'); foobar.innerHTML = 'Foo bar'; foobar.id = 'foobar'; document.body.appendChild(foobar); function displayFoobar() { let e = document.getElementById('foobar'); setTimeout(function () { e.style.color = 'blue'; }, 1000); setTimeout(function () { e.style.color = 'black'; }, 2000); }
<html> <head> <title>Test</title> </head> <body> <h1>Foo bar app</h1> <button onclick="displayFoobar();">display foobar</button> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.