Reputation: 11452
I have dynamically generated html thru ajax when a page is loading, something like this,
<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.
<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.
<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.
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,
<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);
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.
Upvotes: 1
Views: 2697
Reputation: 1520
You may need to post a full blown use case for me to fully understand, but I think that the whole issue is that you're referencing methods that don't exist.
My use case worked fine like this:
<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>
With this JS:
var pElement = document.getElementById('click');
alert(pElement.parentNode);
Upvotes: 0
Reputation: 700152
You can only append DOM elements to an element, you can't append HTML code in a string.
Create an element, use the innerHTML
method to put the HTML code in it, then get the first child node from it to get the p
element as a DOM element.
var div = document.createElement('DIV');
div.innerHTML = data.expandTreeVal;
var p = div.childNodes[0];
Then you can add it to the document using the parentNode
and appendChild
methods:
pElement.parentNode.appendChild(p);
Demo: http://jsfiddle.net/AfVfE/
Upvotes: 2