How can I get every tag “a” that the “href” attribute contains the word “youtube”?

I want to catch every a tag in which the href attribute contains the word youtube . I need to use jquery.

+6
source share
5 answers
 $('a[href*="youtube"]') 

For more selectors, see the Selectors part of the jQuery API.

+14
source

The attribute contains a selector :

 $('a[href*="youtube"]'); 
+9
source

You can always use a "filter":

 var allYoutubes = $('a').filter(function() { return /youtube/.test(this.href); }); 

You can use the fancier selector, but it's simple and clear, and possibly faster, since the library doesn't have to do the work of figuring out what your selector means. This is a matter of taste mainly.

+6
source

pretty simple ...

 $('a[href*="youtube"]') 

http://api.jquery.com/attribute-contains-selector/ http://api.jquery.com/category/selectors/

+4
source

These other answers are great; but in case you are interested, it is not so difficult to make a clean alternative to JS (without jQuery)

 function getYouTubeLinks() { var links = document.getElementsByTagName("a"); var ytlinks = []; for(var i=0,l=links.length;i<l;i++){ if(links[i].href.replace("http://","").indexOf("youtube.com") === 0) { ytlinks.push(links[i]); } } return ytlinks; } var youtube = getYouTubeLinks(); for(var i=0,l=youtube.length;i<l;i++){ youtube[i].style.color = "pink"; } 

It would be nice to cut the "www". and "https: //".

+2
source

Source: https://habr.com/ru/post/892408/


All Articles