Tonani
Tonani

Reputation: 78

Return value of each element

I'm new in jQuery and i have some trouble get this thing works.

<ul id="mediaGallery">
    <li><a href="#">https://www.youtube.com/watch?v=YVw7eJ0vGfM</a></li>
    <li><a href="#">https://www.youtube.com/watch?v=LW0k4eOEJ4U</a></li>
    <li><a href="#">https://www.youtube.com/watch?v=_SM7jtNOTXg</a></li>
</ul>

The idea is to get the last part of the url (ex: YVw7eJ0vGfM), empty the <a> element and replace it whith an <img> and returning the last part of the url at the end of the src path of the image in order to display a thumbnail of the youtube video dynamically.

//get the content of the <a> element
var video_href = $('#mediaGallery li a').html();

//get the last part of the url
var id_video = video_href.substr(video_href.length - 16);

//predifined img html whith the id of the video
var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

//empty the <a> element
$('#mediaGallery li a').empty();

//insert the img var
$('#mediaGallery li a').append(img_path);

The problem is that only the first video id is returned and pasted in all <a>.

How can i return each video id not just the first one?

Any help would be greatly apreciated
Thanks.

Upvotes: 0

Views: 100

Answers (4)

nullable
nullable

Reputation: 2571

Wrap this in an $.each:

$('li a','#mediaGallery').each(function() {
    var me = $(this),
        id = me.html().substr(video_href.length - 16);
    me.empty().append($('<img />').attr('src', 'http://img.youtube.com/vi/'+id+'/0.jpg')
});

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

What if the video has other parameters after the id? I'd suggest you extract the id with a simple regex on each link iterating with each.

$('#mediaGallery li a').each( function() {
  var id = /\?v=(\w+)/.exec( $(this).text() )[1];
  ...
});

That should help you get on the right path.

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

Use a $.each loop

$('#mediaGallery li a').each(function(){
    var video_href = $(this).html();
    var id_video = video_href.split("=")[1];

    var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

    $(this).empty().html(img_path);

});

Check Fiddle

Upvotes: 0

malificent
malificent

Reputation: 1441

you need to use an each loop:

 $("#mediaGallery li a").each(function() {
    //get the content of the <a> element
        var video_href = $(this).html();

        //get the last part of the url
        var id_video = video_href.substr(video_href.length - 16);

        //predifined img html whith the id of the video
        var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

        //empty the <a> element
        $(this).empty();

        //insert the img var
        $(this).append(img_path);
    }

Upvotes: 0

Related Questions