I have dynamically generated html thru ajax when a page is loading, something like this,
Dynamically inserted,
<p class="Hello">
<span id='click lvl1'>1</span>
<span>2</span>
</p>
Now, I am trying to add another node into my <p> element. Again, dynamically thru ajax.
Server response is something like,
<p class="Hello lvl2">
<span id='click'>1</span>
<span>2</span>
</p>
Which I want to insert into the element which I have got first time.
final result,
<p class="Hello">
<span id='click'>1</span>
<span>2</span>
<p class="Hello lvl2">
<span id='click'>1</span>
<span>2</span>
</p>
</p>
While making an second ajax call I am getting reference to <span id='click lvl1'>1</span> element.
What have I tried so far?
Everthing, I could try I have tried but I am not able to inset the node. I am assuming that I am doing something really wrong. My attempts are,
pElement is <span id='click'>1</span>
pElement.parent().appendChild(data.expandTreeVal);pElement.parent().append(data.expandTreeVal);pElement.parent().after(data.expandTreeVal);pElement.parentNode().appendChild(data.expandTreeVal);
Debugging
Do I really get anything from server?
Yes, When I do alert(data.expandTreeVal); it shows me my desired HTML.
any thoughts will be a great help.
You can only append DOM elements to an element, you can’t append HTML code in a string.
Create an element, use the
innerHTMLmethod to put the HTML code in it, then get the first child node from it to get thepelement as a DOM element.Then you can add it to the document using the
parentNodeandappendChildmethods:Demo: http://jsfiddle.net/AfVfE/