我有以下代码,它将HTML标记简单地解析为DOM对象。使用id检索嵌套在另一个元素中的元素
var html_str = '<div id="body-wrapper">\
<div id="container-1">\
<p>This is the first container - Line 1</p>\
<p>This is the first container - Line 2</p>\
<p><img src="assets/img/pull_1.jpg"></p>\
</div>\
<div id="container-2">\
<p>This is the second container - Line 1</p>\
<p>This is the second container - Line 2</p>\
<p>This is the second container - Line 3</p>\
<p><img src="assets/img/pull_2.jpg"></p>\
</div>\
<div id="container-3">\
<p>Test</p>\
<p><img src="assets/img/pull_3.jpg"></p>\
</div>\
</div>';
var elem_obj = document.createElement("div");
elem_obj.innerHTML = html_str;
如何从elem_obj
内获得与id == container-1
元素?只有香草JavaScript和elem_obj.querySelector('#container-1')
以外的东西,因为我需要支持低于版本8的IE。
谢谢。
你是如何得到这些多JS字符串工作? – Xufox
创建一个'DocumentFragment'。然后你可以使用'docFrag.getElementById'。 http://stackoverflow.com/questions/1643349/is-there-any-way-to-find-an-element-in-a-documentfragment – Amadan
@Xufox:Doh。太多的jQuery,我几乎从来没有使用纯DOM再多...谢谢,修复。 – Amadan