Obi*_*ill 3 html javascript dom
我在尝试着:
我有以下代码:
$(document).ready(function(){
function _parse(html_str_or_obj)
{
var elem_obj, elem_dom_obj;
//Convert to DOM element
elem_obj = document.createElement("div");
elem_obj.innerHTML = html_str_or_obj;
elem_dom_obj = elem_obj.firstChild;
return elem_dom_obj;
}
var html_str = '<div id="body-wrapper">\
<div id="container-1">\
<div id="container-1x"><div id="container-2x"><div id="container-3x"><p>First Paragraph</p></div></div></div>\
<p>This is the first container - Line 1</p>\
<p>This is the first container - Line 2</p>\
<p>This is the first container - Line 3</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>This is the second container - Line 4</p>\
</div>\
<div id="container-3">\
<p>This is the third container - Line 1</p>\
<p>This is the third container - Line 2</p>\
</div>\
</div>';
var elem_body_obj = document.body;
var elem_obj = _parse(html_str);
var elem_p_obj = elem_obj.getElementsByTagName('p');
for(var i = 0; i < elem_p_obj.length; i++)
{
elem_body_obj.appendChild(elem_p_obj[i]);
}
});
Run Code Online (Sandbox Code Playgroud)
当我附加元素时,它可以工作。它只附加了 5 个段落而不是 10 个段落。不确定发生了什么。
当我使用 时console.log(elem_p_obj),它会显示一个只有 5 个元素的 HTMLCollection。但是,当我elem_body_obj.appendChild(elem_p_obj[i]);从 for 循环中注释掉时,它照常输出 10 个元素。
我想附加所有 10 个段落,但似乎有什么地方不对劲。
这是一个小提琴:http : //jsfiddle.net/o3gutw2e/3/。
element.getElementsByTagName 返回活动节点列表。这意味着在将每个项目附加到正文后,您的列表正在缩小。
您可以简单地继续在第一个元素上调用 appendChild ,而不是遍历列表,而不管列表的原始大小有多长。
while (elem_p_obj.length > 0)
{
elem_body_obj.appendChild(elem_p_obj[0]);
}
Run Code Online (Sandbox Code Playgroud)
实时节点列表往往会在应用程序中引入许多意外错误,因此我建议改用带有 querySelectorAll 的原始解决方案。
var elem_p_obj = elem_obj.querySelectorAll('p');
for(var i = 0; i < elem_p_obj.length; i++)
{
elem_body_obj.appendChild(elem_p_obj[i]);
}
Run Code Online (Sandbox Code Playgroud)