If i have a variable lets say
var id = //something dynamically generated
then i have <a href="http://localhost/ (the variable id)"
How do i go about this?
The concatenation cannot occur within the anchor tag itself, but you can set it like this:
<a id="my_anchor" href=""></a>
<script type="text/javascript">
// jQuery way
$( "#my_anchor" ).attr( 'href', 'http://localhost/' + id );
// Non-jQuery way
document.getElementById( "my_anchor" ).href = 'http://localhost/' + id;
</script>
Nobody has pointed out you should always do encodeURIComponent when you set things like this; otherwise you leave yourself open to script injection attacks:
Taking @jayp's example:
<a href="#" id="mylink">My Link</a>
var id = getSomethingDynamic();
var url = "http://localhost/" + encodeURIComponent(id);
document.getElementById("mylink").href = url;
Something like this:
<a href="#" id="mylink">My Link</a>
var id = // something dynamic
var url = "http://localhost/"+id;
document.getElementById("mylink").href = url;
You don't have to wait for the document to have fully loaded, in most cases as long as the element has been loaded into the DOM you will be fine assuming that your Javascript is placed after the element (like above).
Not good practice, but it's misleading to say you "have" to wait for the whole page to be loaded. You don't.
You can just retrieve the DOM element, and add something to the href property. Like this:
<script type='text/javascript'>
var id = 5;
window.onload = function()
{
document.getElementById('url').href += id;
}
</script>
<a href='http://localhost/?id=' id='url'>Click me</a>
You have to wait for the document to load in order to get the element, it would not exist otherwise.
<script> tag after the <a> tag. Furthermore, overriding window.onload is very bad practice. -1window.onload is not bad practice, sure if you use jQuery or the likes there probably is some function to handle the onload request. Its the only way.