Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById to include href

<script type="text/javascript">
document.getElementById("IDOFELEMENT");
</script>

What is the correct way to turn this into a link?

Can I write

<script type="text/javascript">
document.getElementById("IDOFELEMENT").href("http://www.address.com");
</script>

Many thanks.

like image 756
RCNeil Avatar asked May 15 '26 20:05

RCNeil


2 Answers

javascript:

// this changes the href value<br>
document.getElementById("IDOFELEMENT").href = "http://www.address.com";

and the html:

<a href="www.toBeChanged.com" id="IDOFELEMENT">To Website< /a>
like image 127
mimmo Avatar answered May 19 '26 03:05

mimmo


You should specify what kind of element is IDOFELEMENT. But you can't convert it to a link by just adding a href attribute, it only works if IDOFELEMENT is an hyperlink like <a id="IDOFELEMENT">stuff</a>

Simplest way is to add an onclick event to the element that changes the url to desired address:

<script type="text/javascript">
   var element = document.getElementById("IDOFELEMENT");
   element.setAttribute('onclick', 'window.location.href=\'http://address.com\'');
</script>

Or if you wanna wrap it with a hyperlink:

<script type="text/javascript">
   var element = document.getElementById("IDOFELEMENT");
   var parent = element.parentNode; 
   var link = document.createElement('a');
   link.href = 'http://www.address.com';
   link.appendChild(element.cloneNode(true)); 
   parent.replaceChild(link, element);
</script>

I hope this helps you.

like image 39
Skatox Avatar answered May 19 '26 02:05

Skatox