0

I am trying to fetch some data from youtube api and display the same on my webpage.

But for some reason, The DOM which I am changing inside the getJSON's callback does not change. In the console, when I print $el, I can see the html code in the variable. But it doesn't show up on the page nor in the view source (elements) tab.

I can't add Classes, remove Classes, or any DOM operation inside it. I'm curious about this because I have used the same thing elsewhere and it worked.

If after the page loads, I do the same thing by running this function in command line, it works perfectly.

Here is the code I am trying to use :

get_ytube = function(els){
    var $els = $(els)
    $.each($els, function(i, v) {
        var $v = $(v)
        var id = $v.data("link-id")

        var url = "http://gdata.youtube.com/feeds/api/videos/" + id + "?v=2&alt=jsonc"

        $.getJSON(url, function(json) {
            var $el = $v

            $("<h5 class='title'>" + json.data.title + "</h5>" + 
                "<p class='desc'>" + json.data.description + "</p>").appendTo($el)
            console.log($el[0])
        });
    })
}
AbdealiLoKo
  • 3,261
  • 2
  • 20
  • 36

1 Answers1

0

Maybe you just need to execute it after the window has been loaded?

$( document ).ready(function() {
  // put your code here
});

Actually looking closer at this it looks like you're just missing a bunch of semicolons so javascript is interpreting your code incorrectly. This post explains why Do you recommend using semicolons after every statement in JavaScript?.

I added them and tried it myself and it works for me. Take a look at this http://jsfiddle.net/gx3Us/.

var get_ytube = function(els) {
    var $els = $(els);
    $.each($els, function(i, v) {        
        var $v = $(v);
        var id = $v.data("link-id");
        var url = "http://gdata.youtube.com/feeds/api/videos/" + id + "?v=2&alt=jsonc";
        $.getJSON(url, function(json) {
            var $el = $v;
            $("<h5 class='title'>" + json.data.title + "</h5>" + "<p class='desc'>" + json.data.description + "</p>").appendTo($el);
            console.log($el[0]);
        });
});

}

Community
  • 1
  • 1
ctown4life
  • 835
  • 1
  • 11
  • 24