0

I have a function that will create a new Youtube iframe for each JSON object.

var createYTPlayer = function () {

        var ytVidPlayer = $("<iframe/>");
        var videoId = raw_content.media[counter].video;

        ytVidPlayer.attr({
            height: 315,
            width: 560,
            src: 'https://www.youtube.com/embed/' + videoId,
            frameborder: 0
        });

        return ytVidPlayer;

    };

The video function gets the returned YT player object from createYTPlayer function.

var video = function () {

        // Development
        console.log('shortcodeController.video');

        var outputHTML;
        var ytPlayer;

        if (raw_content.media[counter].video != undefined) {

            outputHTML = '<div class="video">';

            // Youtube object
            ytPlayer = createYTPlayer();
            console.log('youtube player: ', ytPlayer);
            outputHTML += ytPlayer;
            outputHTML +='</div>';

            console.log(outputHTML);

            return outputHTML;

        };

    };

Then it should covert the object to a string, because I receive the error in my string as [object Object]. And I will add it to a JSON object that contains text. It will replace then a specific character from the JSON text with the output of the function video, that returns the new video object.

How can I solve this?

Caspert
  • 4,271
  • 15
  • 59
  • 104
  • 1
    guessing but if you revrite your code to use $.append (http://api.jquery.com/append/) you won't need to convert it to string – Matej Žvan Dec 03 '15 at 12:22
  • Possible duplicate of [How do you convert a jQuery object into a string?](http://stackoverflow.com/questions/652763/how-do-you-convert-a-jquery-object-into-a-string) – Adi Darachi Dec 03 '15 at 12:30

3 Answers3

1

Take a look at this answer, which describes how to 'convert' a jQuery object into its string representation. Here it is, tailored to your use-case:

outputHTML += ytPlayer.prop('outerHTML');
sdgluck
  • 24,894
  • 8
  • 75
  • 90
1

You can't just concat objects to strings, You need to get the html of the element, not the object it self. You can get the outer html of the element using the 'outerHTML' function

MDN - element.outerHTML()

Replace

outputHTML += ytPlayer;

with

outputHTML += $(ytPlayer)[0].outerHTML;
Adi Darachi
  • 2,137
  • 1
  • 16
  • 29
-1

You can stringify the object, but is only for debug purposes I guess.

 JSON.stringify(ytPlayer);
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69