Google Bot Google Bot - 5 months ago 22
HTML Question

Unable to append multiple sub-divs inside the main-div?

Here iam having an object and i wany to create a main-div around all messages and for each individual message i want to create a sub-div.But instead iam creating sub-div and it is just wrapping the content.

Desired Structure:

<div class ="main-div">
<div class="sub-div"> .... </div>
<div class="sub-div"> .... </div>
<div class="sub-div"> .... </div>
<div class="sub-div"> .... </div>
<div class="sub-div"> .... </div>
</div>


Output got:

<div class="main-div>
<div class="sub-div"> .... </div>
</div>


Here iam including the js snippet(only necessary part is included)

$('#message').append('<div class="main-div"></div>')
for (var messages in message_object){

var inner = message_object[messages]

$('.main-div').append('<div class="sub-div"></div>')

$('.sub-div').append('<div class="faculty">'+inner.Faculty+'</div>')
$('.sub-div').append('<div class="course">'+inner.Course+'</div>')
$('.sub-div').append('<div class="message">'+inner.Message.replace(/[^\x20-\x7E]/gmi, "")+'</div>')
$('.sub-div').append('<div class="sent">'+inner['Sent On']+'</div>')
$('.sub-div').append('<hr />')

}


message_object console is here : https://api.myjson.com/bins/59blv

Answer

Try the following:

var html ='<div class="main-div">';
    for (var messages in message_object){

            var  inner = message_object[messages]

            html+='<div class="sub-div">';
            html+='<div class="faculty">'+inner.Faculty+'</div>';
            html+='<div class="course">'+inner.Course+'</div>';
            html+='<div class="message">'+inner.Message.replace(/[^\x20-\x7E]/gmi, "")+'</div>';
            html+='<div class="sent">'+inner['Sent On']+'</div><hr /></div>';

        }
$('#message').append(html+'</div>');

Demo: https://jsfiddle.net/md9187wr/1/

Comments