htmljqueryanchorurl-fragment

jQuery - Append hash to href from current URL


Let's say I have this URL in the address bar:

www.example.com/pt.html#myhash

Also I have an anchor that links to

<a id="lang" href="https://www.example.com/en.html">Change Language</a>

What I wanted to archive is to append to that anchor the #myhash tag but only if it's present in the current URL. If not, don't append anything.


Solution

  • Check if window.location.hash is set and that it isn't just a '#' then apply to the anchor

    // for demo only set hash
    history.pushState(null, null, '#someVal')
    
    
    const urlHash = location.hash,
         langLink = document.querySelector('#lang');
    
    if (urlHash && urlHash !== '#') {
      langLink.hash = urlHash; 
    }
    
    console.log('New href=',langLink.href)
    <a id="lang" href="https://www.example.com/en.html">Change Language</a>