walkcc
walkcc

Reputation: 311

How to append a div to a container

I implemented a chatroom by HTML and Javascript recently.

I don't know how to append the message(class="chat self") to the "chat-container" when I click the button "Send".

Here is the code:

    <div id = "chat-container" class="chat-container">
        <div class="chat friend">
            <div class="user-photo"><img src="images/james.jpg"></div>
            <p class="chat-message">How are you?</p>                
        </div>
        <div class="chat self">
            <div class="user-photo"><img src="images/curry.jpg"></div>
            <p class="chat-message">Fine, thx!</p>              
        </div>
        <div class="chat friend">
            <div class="user-photo"><img src="images/james.jpg"></div>
            <p class="chat-message">How old are you?</p>            
        </div>
    </div>

    <div class="chat-form">
        <textarea id="myTextarea" placeholder="Type your message"></textarea>
        <button onclick="sendMes()">Send</button>
    </div>

My idea is like this:

<script>
    function sendMes() {
        var x = document.getElementById("myTextarea").value;
        document.getElementById("demo").innerHTML = x;
        vara data = 
        '<div class="chat self">
            <div class="user-photo"><img src="images/curry.jpg"></d-wiv>
            <p class="chat-message">Fine, thx!</p>              
        </div>';
        data.chat-message = x;
        document.getElementById("chat-container").appendChild(data);

    }
</script>

I've read a lot of articles about HTML DOM, but they only tell how to change the .innerHTML...

I don't know how to create an div object with class="chat self", and set the object's chat-message to the value in the textarea.

Thanks a lot!

Upvotes: 1

Views: 5937

Answers (1)

riyaz-ali
riyaz-ali

Reputation: 9102

Instead of appending a DOM element to #chat-container you are simply appending a string to it (and that too seems to be malformed)

Maybe you should checkout W3School

A sample implementation of the sendMes() could be like

function sendMes() {
    var message = document.getElementById("myTextarea").value  // maybe try to sanitize it if you are sending it to server

    var messageEl = document.createElement('p')
    messageEl.innerHtml = message;
    messageel.className = "chat-message"

    var userImage = new Image()
    userImage.src = "images/curry.jpg"
    var imageContainer = document.createElement("div")
    imageContainer.appendChild(userImage)
    imageContainer.className = "user-photo"

    var container = document.createElement("div")
    container.appendChild(imageContainer)
    container.appendChild(messageEl)
    container.className = "chat self"

    document.getElementById("chat-container").appendChild(container)

}

Upvotes: 3

Related Questions