document.getElementById to include href

后端 未结 4 486
无人及你
无人及你 2021-01-07 07:08

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

相关标签:
4条回答
  • 2021-01-07 07:21

    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>
    
    0 讨论(0)
  • 2021-01-07 07:26

    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>
    
    0 讨论(0)
  • 2021-01-07 07:36

    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.

    0 讨论(0)
  • 2021-01-07 07:36

    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>
    
    0 讨论(0)
提交回复
热议问题