How can I add “href” attribute to a link dynamically using JavaScript?

前端 未结 5 1200
不思量自难忘°
不思量自难忘° 2020-11-27 14:43

How can I add the href attribute to a link dynamically using JavaScript?

I basically want to add a href attribute to

相关标签:
5条回答
  • 2020-11-27 14:46

    First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

    Then, add something like this in the javascript function that you're calling:

    var abc = 'somelink';
    document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';
    

    This way the link will look like this:

    <a href="somelink">Link</a>
    
    0 讨论(0)
  • 2020-11-27 14:54
    document.getElementById('link-id').href = "new-href";
    

    I know this is an old post, but here's a one-liner that might be more suitable for some folks.

    0 讨论(0)
  • 2020-11-27 14:57
    var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
    a.href = "somelink url"
    
    0 讨论(0)
  • 2020-11-27 15:12

    More actual solution:

    <a id="someId">Link</a>
    
    const a = document.querySelector('#someId');
    a.href = 'url';
    
    0 讨论(0)
  • 2020-11-27 15:13

    I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).

    To add any attribute, just use the setAttribute method on the DOM object:

    a = document.getElementById(...);
    a.setAttribute("href", "somelink url");
    
    0 讨论(0)
提交回复
热议问题