How to Add Query String Parameter to Same Url When on Click a Href Link

<a href> link that adds query parameter to currently existing query parameters

Add an onclick attribute to you a tag and implement the callback getting the event target and merging it with the window.location.

Add Query-String parameter to static link on click

There are many ways you could do this. Below I've listed two very simple methods. Here I'm assuming you already have a reference to your a element (here I've called this element):

Modifying the href attribute
element.href += '?query=value';
Using a click event listener
element.addEventListener('click', function(event) {
// Stop the link from redirecting
event.preventDefault();

// Redirect instead with JavaScript
window.location.href = element.href + '?query=value';
}, false);

HTML anchor link going to the same page with different query string

This should work:

<a href="?z=111">link</a>

I want to append the query string on a URL to all anchor links on the page

How about using querySelectorAll in vanilla javascript instead of jquery. Also, kill your leading '?' in querystring. And if part of your question involves how to get the querystring from the current page's url, use window.location.search.

In the snippet below, you have some google search anchors. One searches 'x', and the other searches 'y'. Your query string further specifies that in both anchors, you want a safe search for images.

// You will use window.location.searchlet querystring = '?tbm=isch&safe=active' 
if(querystring.startsWith('?')) querystring = querystring.replace('?', '');
for(let a of document.querySelectorAll('a')) { a.href += (a.href.match(/\?/) ? '&' : '?') + querystring;}
<a href='https://www.google.com/search?q=x'>search x images safely</a><br/><a href='https://www.google.com/search?q=y'>search y images safely</a>

How to add url parameter to the current url?

There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to:

topic.php?id=14&like=like


Related Topics



Leave a reply



Submit