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);
2
  • 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: developer.mozilla.org/en/DOM/document.getElementById Commented Apr 23, 2012 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 and is universally supported. Commented Apr 23, 2012 at 21:44

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Rather use nextSibling instead of nextNode
Oops, already edited. Thanks anyway :-)
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?

2 Comments

Shouldn't you vote to close it as a duplicate then? ;)
just did.. <excuse> i did update the code to match the OP's code, doesn't that count for something ? :p </excuse>
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);

4 Comments

That actually replaces just the content.
@Amberlamps oops, I mean +=
Using += with innerHTML is an anti-pattern which causes the browser to do a lot more work than required, and wipes out event handlers on the content within. Use appendChild.
@T.J.Crowder thanks for the suggestion, I didn't know it was that bad

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.