我有以下代码,它只是将HTML标记解析为DOM对象。
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;
如何从id == container-1
中获取elem_obj
的元素?仅限香草JavaScript和elem_obj.querySelector('#container-1')
以外的其他东西,因为我需要支持低于版本8的IE。
感谢。
答案 0 :(得分:1)
建议的解决方案(替代DocumentFragment
):您可以使用循环搜索所需的元素。
JSFiddle(查看控制台输出)。
循环如下:
var elem_obj_containers = elem_obj.children[0].children;
// All <div>s with those “container-” IDs
var container1_element=null; // The result or null
for(var i=0;i<=elem_obj_containers.length;i++){
if(elem_obj_containers[i].id=='container-1'){ // Checking for ID
container1_element=elem_obj_containers[i]; // Assigning result
console.log(elem_obj_containers[i]); // Verify result
break; // Show’s over!
}
}
因此,如果找到ID,则该元素将分配给container1_element
,否则该变量将保留null
(与真实document.getElementById
一样)。
从MDN’s page for children
起,它应该一直回到IE6。 IE 6,7和8也包含children
中的HTML注释节点。这应该不是什么大问题。
答案 1 :(得分:1)
正如我在评论中所说的那样,对于对不完整数据的激烈争论表示道歉。虽然旧的IE可以在getElementById
中使用DocumentFragment
,但对于较新的浏览器通常不是这样,因此需要采用混合策略以实现最佳兼容性。
var html = '<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="#"></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="#"></p>\
</div>\
<div id="container-3">\
<p>Test</p>\
<p><img src="#"></p>\
</div>\
</div>';
// from http://stackoverflow.com/a/1643512/240443
function getElementByIdFromNode(node, id) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType !== 1) // ELEMENT_NODE
continue;
if (child.id === id)
return child;
child = getElementByIdFromNode(child, id);
if (child !== null)
return child;
}
return null;
}
// based on http://stackoverflow.com/a/1643383/240443
function getElementByIdFromString(html, id) {
var div = document.createElement("div");
div.innerHTML = html;
// New browsers
if (div.querySelector) {
return div.querySelector("#" + id);
}
// Old IE
var frag = document.createDocumentFragment();
if (frag.getElementById) {
frag.appendChild(div);
return frag.getElementById(id);
}
// Anything else just in case
return getElementByIdFromNode(div, id);
}
var container3 = getElementByIdFromString(html, "container-3");
console.log(container3);