kjkj
kjkj

Reputation: 21

Appending a html list dynamically

This is my HTML code

  <div class="col-lg-12">
    <div class="card">
      <div class="card-header">
        Playlist
      </div>
      <div class="card-body">
        <ul id="playList">
        </ul>
      </div>
    </div>
  </div>
</div>

I tried to request a JSON file and add a list dynamically to the html with this code

function loadVideoList() {
  const playListContainer = $('#playList');
  $.getJSON('http://myserver.com/rest/78', function( res ) {
    const self = this;
    if(this.videoList !== res){
      $('#playList').empty();
      this.videoList = res;
      res.videos.forEach((item) => {
       console.log('ok');
        playListContainer.append('<li class="playlist-item"><span class="playlist-item-link" uri="' + item.name + '">' + item.tcsd + '</span></li>');
      });
    }
    });

The json is downloaded with success, 'ok' is printed n times but the list doese not appear on the html

EDIT: this is a jsfiddle where the problem could be reproduced

Upvotes: 2

Views: 77

Answers (2)

kjkj
kjkj

Reputation: 21

I was calling the javascript before adding the html. I just moved the javascript at the end and it worked

Upvotes: 0

xyiii
xyiii

Reputation: 112

Since you did not provide a fiddle it's kinda hard to help you. But generally, use the ES6 arrow functions for lexical binding. I see you try to imitate it by assigning this to a variable called self, but maybe it's a good idea then to use self instead of this. I guess since you used this in the code blocks it's referencing an undefined object which result in no html to print. Btw the function you provided had a missing }, so I added one.

Try this:

function loadVideoList() {
  let playListContainer = $('#playList');
  $.getJSON('http://myserver.com/rest/78', res => {
    if(this.videoList !== res){
      $('#playList').empty();
      this.videoList = res;
      res.videos.forEach((item) => {
       console.log('ok');
        playListContainer.append('<li class="playlist-item"><span class="playlist-item-link" uri="' + item.name + '">' + item.tcsd + '</span></li>');
      });
    }
    });
}

Upvotes: 1

Related Questions