0

Possible Duplicate:
Inserting an element
How to do insert After() in JavaScript without using a library?

I have this little bit of javascript in a project which adds a chat window after the body of the page, I'd like to change it so that it adds the chat window AFTER my specified div "myPublisherDiv". I think this is pretty simple, any ideas? Thanks in advance!

var div = document.createElement('div');
    div.setAttribute('id', 'stream' + streams[i].streamId);
    document.body.appendChild(div);
Community
  • 1
  • 1
BTHarris
  • 300
  • 3
  • 19
  • Mmh, I just noticed that your title and the text of your question differ... if you only want to append, it seems you just need to learn about `getElementById`: https://developer.mozilla.org/en/DOM/document.getElementById – Felix Kling Apr 23 '12 at 21:40
  • FYI, `div.setAttribute('id', 'stream' + streams[i].streamId);` can be written `div.id = 'stream' + streams[i].streamId;`; [`id` is a *reflected property* on elements](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-63534901) and is universally supported. – T.J. Crowder Apr 23 '12 at 21:44

3 Answers3

1

Put an id to your div

<div id="myDiv">..</div>

And then append things to it with the appendChild:

document.getElementById("myDiv").appendChild(div);
ajax333221
  • 11,436
  • 16
  • 61
  • 95
1

This is a bit trickier. insertBefore is simple, for inserting after a node I wrote a litte helper function:

function insertAfter(newElement, referenceElement) {
    referenceElement.parentNode.insertBefore(newElement, referenceElement.nextSibling);
}

var div = document.createElement('div');
...
insertAfter(document.getElementById("myPublisherDiv"), div);

But see also https://stackoverflow.com/a/1559632/1048572

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

This should do it..

var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);

var target = document.getElementById('myPublisherDiv');

target.parentNode.insertBefore(div, target.nextSibling);

ripped from How to do insert After() in JavaScript without using a library?

Community
  • 1
  • 1
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317