user2059370 user2059370 - 9 months ago 45
Javascript Question

Populate attribute from one element to another element in an each function

How do I populate the iframe src attribute with the href attribute from the

a
element? The iframe can be moved inside the
li.feed-item
element if needed.

I need this in something like an each function, since there are several
li
elements with different links.

Closest I got is this, but it fetches the first link to all iframes.

jQuery(document).ready(function () {
jQuery('li.feed-item').each(function () {
var href = jQuery("li.feed-item a.colorbox.cboxElement").attr('href');
jQuery('li.feed-item a.colorbox.cboxElement iframe').attr('src', href);
});
});


HTML

<ul>
<li class="feed-item">
<a class="colorbox cboxElement" href="http://www.youtube.com/embed/Tp-VAe59RyA"><img height="280" src="http://skateflix.se/wp-content/uploads/cache/remote/i1-ytimg-com/1384690600.jpg" width="280">
<iframe allowfullscreen class="video-embed" height="100%" itemprop="video" src="http://www.youtube.com/embed/werwerw4wer" width="100%">
</iframe></a>
</li>
</ul>

<ul>
<li class="feed-item">
<a class="colorbox cboxElement" href="http://www.youtube.com/embed/Tp-VAe59RyA"><img height="280" src="http://skateflix.se/wp-content/uploads/cache/remote/i1-ytimg-com/1384690600.jpg" width="280">
<iframe allowfullscreen class="video-embed" height="100%" itemprop="video" src="http://www.youtube.com/embed/Qq0u6vbzXXoeerer" width="100%">
</iframe></a>
</li>
</ul>

Answer Source

Basically refer always to $(this), the currently iterated li.feed-item

jQuery(function($) { // DOM ready and $ alias secured

  $('li.feed-item').each(function() {
     var href = $(this).find("a.cboxElement").attr('href');
     $(this).find("iframe").attr('src', href);
  });

});

Or even simpler, query first for your iframe and than lookup for the a parent:

jQuery(function($) { // DOM ready and $ alias secured

  $('li.feed-item iframe').attr("src", function() {
     return $(this).closest("a.cboxElement").attr('href');
  });

});