How do I get the first youtube video of each and store them into an array using jQuery?
HTML:
<div id="one">
<ul class="thumbs">
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</div>
<div id="two">
<ul class="thumbs">
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</div>
I think getting the link would be something like:
$('.thumbs li:first-child').attr("href");
But how do I get both of them and store them into an array?
How do I get the first youtube video of each and store them into an array using jQuery?
HTML:
<div id="one">
<ul class="thumbs">
<li><a href="http://www.youtube./watch?v=-dzpkn29_vY"></a></li>
<li><a href="http://www.youtube./watch?v=xFCRMonf7lI"></a></li>
</ul>
</div>
<div id="two">
<ul class="thumbs">
<li><a href="http://www.youtube./watch?v=UBTUAHGpQqE"></a></li>
<li><a href="http://www.youtube./watch?v=mTkPfjSXFpo"></a></li>
</ul>
</div>
I think getting the link would be something like:
$('.thumbs li:first-child').attr("href");
But how do I get both of them and store them into an array?
Share Improve this question asked Jan 17, 2012 at 23:46 user906080user906080 1252 silver badges11 bronze badges2 Answers
Reset to default 9var arr = $('.thumbs > li:first-child > a').map(function() {
return this.href;
}).toArray();
var arr = [];
$('#one, #two').find('.thumbs').each(function (index, element) {
arr[arr.length] = $(this).find('a[href^="http://www.youtube./watch?v="]').eq(0).attr('href');
});
The bonus of using this type of search is that only elements with links to youtube are added to the array.
The arr
array will now look like this:
["http://www.youtube./watch?v=-dzpkn29_vY", "http://www.youtube./watch?v=UBTUAHGpQqE"]
Note that beginning with the #one
and #two
elements is not necessary (you can start with .thumbs
) however this limits the search to only those elements (in-case there are other .thumbs
elements in the DOM).
Here is a demo: http://jsfiddle/fDQ2v/