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.
            Asked
            
        
        
            Active
            
        
            Viewed 169 times
        
    0
            
            
        - 
                    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 Answers
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
 
    
    
        AlexBay
        
- 1,323
- 2
- 14
- 26
- 
                    This will apply the ID "id" to every new div, which is invalid. IDs must be unique. – George Cummins Sep 07 '11 at 21:04
- 
                    
- 
                    
- 
                    This is the procedure to dynamically generate a new div with an id, generating more is just changing the id, like in my demo – AlexBay Sep 07 '11 at 21:10
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
- 
                    Based on the OP's stated goal, he will likely need to assign a unique ID to each div so chat events can be forwarded to the correct element. – George Cummins Sep 07 '11 at 21:06
- 
                    @George Cummins, I have updated my answer to take into account your suggestion. – Darin Dimitrov Sep 07 '11 at 21:08
