SoMeGoD SoMeGoD - 4 months ago 8
Javascript Question

Check if html <head> contain specific <link>

I'm trying to check if the html head contains this line:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


I was able to find the link element using $('head').find('link'); but I got suck on verifying which one correspond to mine since there're a lot of other links on it.

Is there a way to search the for the whole string, something like (I know the code won't work, it's just an example):

$('head').find('<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">')


Or any other alternatives I'm open to it.

Sorry if this is a lame question, but since I'm on early stages, it's not that lame to me ;)

Answer

Use attribute equals selector for selecting element based on attribute value.

var link = $('head').find('link[href="https://fonts.googleapis.com/icon?family=Material+Icons"][rel="stylesheet"]')
if(link.length){
   // do the rest
}

Or if you would like to compare with the string which contains the element then using filter() method(not tested) do something like.

var link = $('head').find('link').filter(function(){
   return this.outerHTML.trim() == '<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">';
}) 
if(link.length){
   // do the rest
}
Comments