Reputation: 1943
I have a div element generated using javascript :
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm the first div";
Now I have a method which returns me the "div" element to the first created div element(id="block"
). I am just receiving the output from a function(returnDiv()) and I dont have control to change anything inside the method . The output is as follows:
// returnDiv() returns me the following output which I am collecting in innerDiv variable
var innerDiv = <div style="width: 30px;"><div class="pBar" style="width: 100%;"><span title="100.00%" class="l r" style="background: red; left: 1px; width: 30px; box-shadow: 0px 2px 1px rgba(0,0,0,0.2), inset 0px 2px 1px rgba(0,0,0,0.2);" rel="tooltip"></span><span title="0.00%" class=" r" style="background: rgb(255, 194, 0); left: 31px; width: 0px; box-shadow: 0px 2px 1px rgba(0,0,0,0.2), inset 0px 2px 1px rgba(0,0,0,0.2);" rel="tooltip"></span></div></div>;
//document.createElement('div');
//innerDiv.className = 'block-2';
// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);
innerDiv.innerHTML = "I'm the inner div";
Here's the fiddle link : https://jsfiddle.net/1988/5ff8dqbb/
The problem is inner Div is not visible , and the error says "Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. " Since it is runtime I am not able make out whats the problem
Upvotes: 0
Views: 42
Reputation: 704
Better solution:
var parser = new DOMParser()
var el = parser.parseFromString(innerDiv, "text/xml");
iDiv.appendChild(el.firstElementChild)
Old solution:
You can't append inerDiv to iDiv in this way. You can to this like that: Change
`iDiv.appendChild(innerDiv);`
to
`iDiv.innerHTML += innerDiv`
Upvotes: 1