Target iframe if it is a YouTube embed

2020-08-02 05:58发布

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">

4条回答
手持菜刀,她持情操
2楼-- · 2020-08-02 06:46

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楼-- · 2020-08-02 06:53

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>");
});
查看更多
再贱就再见
4楼-- · 2020-08-02 06:57

Can use Attrubute Contains selector

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

Reference Attribute Contains Selector docs

查看更多
放荡不羁爱自由
5楼-- · 2020-08-02 06:57

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

查看更多
登录 后发表回答