document.getElementById to include href

半城伤御伤魂 提交于 2019-12-30 07:41:34

问题


<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.


回答1:


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>



回答2:


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.




回答3:


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>



回答4:


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>


来源:https://stackoverflow.com/questions/10213405/document-getelementbyid-to-include-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!