I'm new to Javascript, and need some help with creating a script that adds 'onclick' to href links of a particular class on an HTML page, upon page load - using the link's href URL, without touching the inline code. The script would modify a regular link, from this
<a href="URL" class="XYZ">
to this:
<a href="#" onclick="location.href='URL';" class="XYZ">
The URL changes for each link but the class remains the same. Here is what I got so far, but I was wondering if it can be improved:
window.onload = function() {
// Saving all links with XYZ-class in a variable
let links = document.getElementsByClassName('XYZ');
// Iterating through the links, changing the onclick attribute
for(let i = 0; i < links.length; i++) {
// Saving the URL
let grabbedURL = links[i].getAttribute('href');
// Putting it in onclick
links[i].setAttribute('onclick', `location.href='${grabbedURL}'`);
// Replacing href with '#'
links[i].setAttribute('href', '#');
}
Here's an approach using a for...of
loop; you can change that if you want:
// iterate through all results of a css selector
for (let link of document.querySelectorAll('a.XYZ')) {
// set onclick attribute as text
link.setAttribute('onclick', 'location.href = ' + JSON.stringify(link.href) + ';');
// set href attribute to empty anchor (#)
link.href = '#';
}
<body>
<a href="https://example.com/" class="XYZ">http://example.com/</a>
<br>
<a href="https://foo.bar/" class="XYZ">http://foo.bar/</a>
</body>
There could be more modern solutions to your problem using EventTarget.addEventListener(), but so far that's what you requested. If you have a question to this answer please write a comment under it.
And as you new to Stack Overflow: If you had a helpful answer for your question, you can mark it as accepted. Of cause only if you want. Doesn't have to be mine.