Rohitesh Rohitesh -4 years ago 88
HTML Question

How can i add href dynamic inside <link> tag

I am trying to display the favicon in the angular 2, i have implemented by putting these lines

<link rel="shortcut icon" type="image/x-icon" href="app/favicon.ico" />


But, in this there is a problem i need to refresh my page and on 2nd time on a new browser its displaying the favicon. But, i want favicon to refresh forcefully and for that i am using

<link rel="icon" href=http://domainname+"/favicon.ico?v=2"/>



For this i need to populate the domain name dynamically


and also i am getting the host name by using the below code

<script>
var url = window.location.href
console.log('Main Loaded '+url);
</script>


Now i want url to be placed inside the href of link where domain name is there .
Please suggest how i can do this.

Answer Source

You can't set the href directly like that, because document.getElementsByTagName returns all the tags (as a NodeList). If you're positive you only have one, use this:

var findlink = document.getElementsByTagName("link");
findlink[0].href = url;

If you have multiple link elements and want to target a specific one, give it an id and use document.getElementById:

var findlink = document.getElementsById("myLinkId");
findlink.href = url;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download