0

I have searched almost whole internet but couldn't able to get a solution about this..

Suppose that we have a div element with some html inside of it. After selecting this tag by its id (or other selectors, whatever) and if I use "innerHTML" method, I lost all html inside of the tag. What can i do to not destroy html parts inside of the tag? I just want to add something "more", not to "destroy all" and then insert something into new instead.

document.getElementById('something').innerHTML = document.getElementById('something').innerHTML + new_html_to_append;

the method above doesn't work for 3rd iteration, or in a for loop so it's useless for me.. i need something fits infinite supplementation.

Thank You!

(I know .append() method but i am not allowed to use JQuery there.)

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123

3 Answers3

0

Using innerHTML() can result in some unexpected behaviour. Look at alternatives like appendChild() from here:

How to append data to div using javascript?

Community
  • 1
  • 1
dKen
  • 3,078
  • 1
  • 28
  • 37
0

Use AppendChild() .In using this function be aware to use the correct functions like if you have to add HTML Element like div.Then Use

obj=document.createElement(something);
document.getElementById("something").appendChild(obj);

But if its a Text Node then

obj=document.createTextNode(something);
document.getElementById("something").appendChild(obj);
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
  • all developers on the project have added something new into code since years that i can't count and now it's a total mess. I can't copy whole code here cos there are a lot of node it contains including an old ajax engine, some parts works only in server, etc. long story short, a total mess. by the way, appendChild works for now, thank you! – Said Bahadır Kaya Jun 07 '13 at 15:01
  • so you mean you don't know whether the something is Element or just text ,right? – bugwheels94 Jun 07 '13 at 15:03
-1

appendChild()

...................................

7stud
  • 46,922
  • 14
  • 101
  • 127