TeaCupApp
TeaCupApp

Reputation: 11452

Appending child node by javascript

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>

  1. pElement.parent().appendChild(data.expandTreeVal);
  2. pElement.parent().append(data.expandTreeVal);
  3. pElement.parent().after(data.expandTreeVal);
  4. 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.

Upvotes: 1

Views: 2697

Answers (2)

thewebguy
thewebguy

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

Guffa
Guffa

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

Related Questions