I am trying to:
- Parse a HTML string to a DOM object
- Extract the paragraphs (10 of them in this case)
- Append extracted paragraphs to body
I have the following code:
$(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]);
}
});
It works up to the point when I append the elements. Instead of 10 paragraphs, it only appends 5. Not sure what is going on.
When I use console.log(elem_p_obj)
, it shows me a HTMLCollection with only 5 elements. However, when I comment out elem_body_obj.appendChild(elem_p_obj[i]);
from the for loop, it outputs 10 elements as normal.
I want to append all 10 paragraphs, but something seems to be wrong somewhere.
Here's a fiddle: http://jsfiddle.net/o3gutw2e/3/.