Duncan Palmer Duncan Palmer - 1 year ago 40
HTML Question

Populating an element with dynamic html

So I am building a song queue which automatically updates it's contents on a function call. This function call creates an ajax request to a php script which returns json data for songs in the queue (image url, song title, song author). I am then wanting to dynamically populate my ul with li's based off each of these songs returned in the json data.

The current structure is a ul containing li's which hold all the other html.

Like so:

<ul>
<li>
<div id="thumbnail" style="background: url('URL HERE'); background-size: 100% 100%"></div>
<div id="songdetails">
<div id="title">TITLE HERE</div>
<div id="author">AUTHOR HERE</div>
</div>
</li>

<li>
<div id="thumbnail" style="background: url('URL HERE'); background-size: 100% 100%"></div>
<div id="songdetails">
<div id="title">TITLE HERE</div>
<div id="author">AUTHOR HERE</div>
</div>
</li>

<li>
<div id="thumbnail" style="background: url('URL HERE'); background-size: 100% 100%"></div>
<div id="songdetails">
<div id="title">TITLE HERE</div>
<div id="author">AUTHOR HERE</div>
</div>
</li>
</ul>


My issue is that from what I have found on stackoverflow and other sites most people suggest something like:

var ul = document.getElementById('ul');

ul.appendChild(child);


My problem with this is that I am trying to minimize the amount of code that I am using to make the code streamline and readable and don't want to have to have variables for each child and their children.

Is there a more efficient way to achieve this?

Answer Source

A jQuery solution:

<ul id="container" />

and Javascript:

// Assuming the data comes in like this:
/*
[
    {url: 'http://www.example/com', title: 'Title Goes Here', author: 'Author here'},
    {url: ...
]
*/
$.getJSON('url.php', function(data) {
    $('#container').empty().append(data.map(function(x) {
        return '
            <li>
                <div id="thumbnail" style="background: url(\'' + x.url + '\'); background-size: 100% 100%"></div>
                <div id="songdetails">
                    <div id="title">' + x.title + '</div>
                    <div id="author">' + x.author + '</div>
                </div>
           </li>
        ');
    });
});