Let’s say that instead of looking at the ID, I want to select all a.href
elements that contain (a piece of) this example: if document.url
is "www.youtube.com"
.
var youtubeID = document.querySelectorAll('.youtubelink');
var youtubeDiv = document.querySelectorAll('a[href^="http://www.youtube.com"]');
2
Answers
You can use
*
wildcard which matches any attribute value wherehttps://www.youtube.com
appears anywhere in the string.Use this selector
a[href*="https://www.youtube.com"]
@YuvarajM’s example selects the given link even if it contains only part of url (example:
anothersite.com?link=www.example.com
). Additionally, it will not select it if it is written with thehttp://
protocol instead ofhttps://
, or if thewww.
part is not included.Although this solution is correct, you may want to set stricter rules, which, however, is not possible using
querySelector
.Solution
Using regex allows for even more unique and stringent rules to be specified.
With my example, it will select all your hyperlinks regardless of the protocol and http://www., which are:
example.com
(without protocol and www.)www.example.com
(without protocol)http://example.com
(without www.)http://www.example.com
https://example.com
(without http://www., with a different protocol)https://www.example.com
More information
querySelectorAll()
method – MDN DocsArray.from()
– MDN DocsArray.prototype.filter()
– MDN Docs