简体   繁体   中英

What is the best way to get current url string in an html a tag?

I have the below block of code and I want to use javascript to check if current url string has "?mall", then I will add that to my href attribute in the tag. What is the best way to go about it?

<div>
  <div>
    <a href="/" role="button">My Link</a>
       My Page
  </div>
  <div id="my-list"></div>
</div>

This would check if the string 'mall' in the query string (everything behind ? ). If it is, it will try to locate the <a> tag with an href="/" attribute.

If that tag is found it adds ?mall to the current href attribute value.

if (location.search.includes('mall')) {
  const anchor = document.querySelector('a[href="/"]');
  if (anchor) {
    anchor.href += '?mall';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM