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', '#');
}