Target iframe if it is a YouTube embed

2020-08-02 06:48发布

问题:

I want to wrap all YouTube embeds on the page into a div. Currently, I can wrap all iframes in a div with:

   jQuery(document).ready(function(){

    jQuery('iframe').wrap("<div class='ta-vid-cont'></div>");

   });

But I want to target only iframes that are YouTube Embeds. How can I do this?

Typical YouTube embed looks like:

<iframe width="700" height="394" frameborder="0" allowfullscreen="" src="https://www.youtube.com/embed/d3LDQMKLc?feature=oembed&wmode=transparent">

回答1:

Can use Attrubute Contains selector

$('iframe[src*="youtube"]').wrap("<div class='ta-vid-cont'></div>");

Reference Attribute Contains Selector docs



回答2:

you could use filter() in combination with a regex filtering via the source url:

jQuery('iframe').filter(function(){
    return this.src.match(/youtube\.com/i);
}).wrap("<div class='ta-vid-cont'></div>");

fiddle: http://jsfiddle.net/0hhk9kc5/1/

(since jsfiddle won't show iframes for security reasons, i changed the filtering to another attribute...but the idea is the same ;) )

[EDIT]: for covering youtu.be:

jQuery('iframe').filter(function(){
    return this.src.match(/(youtube\.com|youtu\.be)/i);
}).wrap("<div class='ta-vid-cont'></div>");

explanation of the used regex: https://regex101.com/r/dU0bF2/1



回答3:

I think you can search in src attribute of iframe for "www.youtube.com"

var str=$('iframe').attr('src');  
if(str.search('www.youtube.com') > 0){  
......
....  
};

Regards



回答4:

you can easily assign each iframe an id and grab it with jQuery<iframe id="youtube" width="700" height="394" frameborder="0" allowfullscreen="" src="https://www.youtube.com/embed/d3LDQMKLc?feature=oembed&wmode=transparent">

$(document).ready(function(){

    $('#youtube').wrap("<div class='ta-vid-cont'></div>");
});