RCNeil
RCNeil

Reputation: 8759

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.

Upvotes: 3

Views: 70579

Answers (4)

Declan
Declan

Reputation: 21

I came accross the issue - Javascript error: Cannot read property 'parentNode' of null. I discovered this was due to executing this code while the DOM is not ready. window.onload solved the issue for me.

<script>
window.onload = function() {

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

Upvotes: 2

mimmo
mimmo

Reputation: 96

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>

Upvotes: 8

mayhewr
mayhewr

Reputation: 4021

You just need to wrap your element in an anchor tag as follows...

<a href="http://www.address.com">
    <div id="IDOFELEMENT">
    ... content ...
    </div>
</a>

Upvotes: 0

Skatox
Skatox

Reputation: 4284

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.

Upvotes: 3

Related Questions