M.Anokye
M.Anokye

Reputation: 23

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>

Upvotes: 0

Views: 164

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20954

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';
  }
}

Upvotes: 1

Related Questions