0

I'm writing a chat function that one user might chat with multiple ones at one time, which need generate multiple div to load the chat page. Typically, I just write div with an id there, and call it using jQuery. Now, since I don't know how many div need to be called at the same time, I can not write it in advance. Any idea? Or if you have better solution, let me know too. Thank you very much.

Steven Zack
  • 4,984
  • 19
  • 57
  • 88
  • You should be able to dynamically insert a `div` element into your page by first selecting the parent element and using the `.append("
    stuff
    )`. See [this](http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery) for more info.
    – Kris Schouw Sep 07 '11 at 21:04

3 Answers3

1

This method will allow you to assign unique IDs to each chat div so you can send the chat output to the specific page elements.

var number_of_chat_sessions = 4; // Adjust according to your needs, or assign programmatically

for ( var i=0; i<number_of_chat_sessions; i++) {
    var chat_div = $( "<div>Initial output here</div>" ).attr( "id" , "chat_session_" + i );
    $( "#chat_container" ).append( chat_div );
}
George Cummins
  • 28,485
  • 8
  • 71
  • 90
0

Without jQuery need:

var newDiv = document.createElement('div');
newDiv.setAttribute('id', "your_current_id");
wrapper.appendChild(newDiv);

wrapper is the JavaScript object that will contain the div

Demo here

AlexBay
  • 1,323
  • 2
  • 14
  • 26
0
for (var i = 0; i < 10; i++) {
    $('body').append(
        $('<div/>', {
            id: 'element_' + i,
            html: 'item ' + i
        })
    );
}

Demo.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928