Using JavaScript variable inside an anchor tag's href attribute
html, javascript
Solution
Assume you have the following in your HTML
<a href="link" class='dynamicLink'>link</a>
<a href="link" class='dynamicLink'>link</a>
You can do the following
var href = 'http://www.google.com'; //any other link as wish
var links = document.getElementsByClassName('dynamicLink');
Array.from(links).forEach(link => {
link.href = href;
link.innerHTML = href.replace('http://', '');
});
JSFiddle
Problem
Consider I have a JavaScript variable named `link` which contains a URL like this: `www.google.com`. I need to include this variable in `href` attribute in 2 places, like: ``` <a href="link">link</a> ``` This should return something like this: Google I tried various ways but failed. Is it possible to do like this? The JavaScript variables should be used at both places. Note: I need to use the variable inside `<a>` tag also