1

I am filling a div dynamically. But I am having problems with the placement of innerHTML. The code below will make it clear.

 function update() {
    $.ajax({
    url: '/update/',
    type:"POST",
    cache:false,
    success: function(data) {
        alert(JSON.stringify(data));
        var ul = document.createElement('ul');
        var div = document.getElementById('rightbar');
        for(var i = 0; i < data.length; i++) {
            var li = document.createElement('li');
            var a = document.createElement('a');
            var img = document.createElement('img')
            a.innerHTML = data[i]['fields']['video_title'];
            a.target = "_blank";
            a.href = data[i]['pk'];
            img.src = "media/" + data[i]['fields']['video_thumbnail'];
            a.appendChild(img);
            li.appendChild(a);
            ul.appendChild(li);
        }
        div.innerHTML = "";
        div.appendChild(ul);
    },
    failure: function(data) { 
        alert('Got an error dude');
    }
}); 

This gives me the HTML of following form:

<div id = "rightbar">
<ul>
<li><a href = "video_link">video_title<img src = "video_thumbnail"></a></li>
</div>

But what I want is the following:

<div id = "rightbar">
<ul>
<li><a href = "video_link"><img src = "video_thumbnail">video_title</a></li>
</div>

Notice the placement of "video_title" in both the HTML.

Shivam Mitra
  • 1,040
  • 3
  • 17
  • 33

1 Answers1

1

        var data=[1]; // just for the example to work
   
        var ul = document.createElement('ul');
        var div = document.getElementById('rightbar');
        for(var i = 0; i < data.length; i++) {
            var li = document.createElement('li');
            var a = document.createElement('a');
            var img = document.createElement('img')
            var video_title = document.createElement('span');
            video_title.innerHTML = 'video_title'; // data[i]['fields']['video_title'];
            a.target = "_blank";
            a.href = 'href'; // data[i]['pk'];
            img.src = "media/" + ''; // data[i]['fields']['video_thumbnail'];
            a.appendChild(img);
            a.appendChild(video_title);
            li.appendChild(a);
            ul.appendChild(li);
        }
        div.innerHTML = "";
        div.appendChild(ul);
<div id='rightbar'></div>
Slonski
  • 824
  • 5
  • 12