简体   繁体   English

将HTML解析为DOM,以便稍后由getElementById访问

[英]Parsing HTML into DOM to be later accessed by getElementById

Example of code: 代码示例:

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;

example of code with DOMParser DOMParser的代码示例

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

in whatever way, I cannot access to the element through 无论如何,我都无法通过

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

What options do I have? 我有什么选择? I would not want to write the select_x nodes in a DOM-like style, since html code written in that way would lose all understand-ability IMHO 我不想以类似DOM的样式编写select_x节点,因为以这种方式编写的html代码将丢失所有可理解性恕我直言

*The parent_1 node is appended onto a real HTML node such as document.getElementById('html_element').parentElement.appendChild(parent_1); * parent_1节点附加到真实的HTML节点上,例如document.getElementById('html_element').parentElement.appendChild(parent_1);

EDIT: solved By using querySelector, for example 编辑:例如,通过使用querySelector解决

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

Solved By using querySelector (see edited question), for example 例如,通过使用querySelector解决(请参阅已编辑的问题)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM