gpt4 book ai didi

javascript - 将 HTML 解析为 DOM,以便稍后通过 getElementById 访问

转载 作者:行者123 更新时间:2023-11-30 12:16:39 24 4
gpt4 key购买 nike

代码示例:

var new_node = document.createElement('div');
new_node.id = 'parent_1';

var html = '<div id="select_1">hey</div>'+
'<div id="select_2">hey</div>';

new_node.innerHTML = html;

使用 DOMParser 的代码示例

var parser = new DOMParser();
new_node.appendChild(parser.parseFromString(html, "text/html").documentElement);

无论以何种方式,我都无法访问该元素

console.log(document.getElementById('select_1')); //null
// but I can with the DOM-like node (appended to the document)
console.log(document.getElementById('parent_1')); //correct

我有哪些选择?我不想以类似 DOM 的样式编写 select_x 节点,因为以这种方式编写的 html 代码将失去所有可理解性恕我直言

*parent_1 节点附加到真实的 HTML 节点上,例如document.getElementById('html_element').parentElement.appendChild(parent_1);

编辑:已解决例如,通过使用 querySelector

var parser = new DOMParser();
var temp = parser.parseFromString(html, "text/html").documentElement;
console.log(temp.querySelector('#select_1')); //correct
new_node.appendChild(temp);

最佳答案

例如,通过使用 querySelector 解决(参见已编辑的问题)

var parser = new DOMParser();
var temp = parser.parseFromString(html, "text/html").documentElement;
console.log(temp.querySelector('#select_1')); //correct
new_node.appendChild(temp);

关于javascript - 将 HTML 解析为 DOM,以便稍后通过 getElementById 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32272447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com