I have those code in one HTML document:
<div class="linksblock">
<a link href="www.google.com/1">link 1</a>
<a link href="www.google.com/2">link 2</a>
<a link href="www.google.com/3">link 3</a>
<a link href="www.google.com/4">link 4</a>
<a link href="www.google.com/5">link 5</a>
</div>
I would like the links in the "linksblock" to be supplemented with the "?=PAT" tag.
For example, when I open the first link, it should not open "www.google.com/1" but "www.google.com/1?=PAT" yes.
So is there any way to supplement the links?
Important: I'm aware that I could write it at the end of the links, but I have 8,000 such pages where I would like to apply the addition specifically to this div block.
Just add this JavaScript code to your html.
document.addEventListener("DOMContentLoaded", function () {
const links = document.querySelectorAll('.linksblock a');
links.forEach(link => {
const href = link.getAttribute('href');
if (href) {
if (!href.includes('?=PAT')) {
// Check if URL already has a query string
const separator = href.includes('?') ? '&' : '?';
link.setAttribute('href', href + separator + '=PAT');
}
}
});
});
const links = document.querySelectorAll('.linksblock a');
will get all the elements inside with class linksblock,
links.forEach(link => {}
Loops through each element found
if (href) {
Checks that the href isn't null or empty
if (!href.includes('?=PAT')) {
Ensures ?=PAT is not already present, this is to avoid duplicating.
const separator = href.includes('?') ? '&' : '?';
link.setAttribute('href', href + separator + '=PAT');
Updates the link’s href by adding ?=PAT or &=PAT at the end
Let me know if you need further explanation to the code? or any other issues if your having?