-2

I am attempting to get all links on a page where the link name and href are the same and assign a value to the return name to make the reference to that link unique.

So if a page had the following three identicial links:

            <a href="link1" class="adobeTrackedCustomLink">About Us</a>
            <a href="link1" class="adobeTrackedCustomLink">About Us</a>
            <a href="link1" class="adobeTrackedCustomLink">About Us</a>

The expected result if second link clicked the return would be:

aboutus-link1-2

I can get the link name and href returned as below:

            var linkname = $(input).text().trim().replace(/\W/g, '').toLowerCase();
            var hrefname = $(input).closest('a').attr("href").replace(/\W/g, '').toLowerCase();
            return linkname + '-' + hrefname;

But I don't know how I would do the ID on the end, any help would be appreciated.

Pete
  • 57,112
  • 28
  • 117
  • 166
bigdaveygeorge
  • 947
  • 2
  • 12
  • 32

1 Answers1

0

I came up with a vanilla js solution. It might be a little verbose, but you can get the id like this:

var q = document.querySelectorAll('.adobeTrackedCustomLink');

for(var i = 0; i<q.length; i++){
      q[i].id = i; 
      var linkname;
      var hrefname;
      var id;
      q[i].addEventListener('click', function(e){
                e.preventDefault();
                linkname = this.textContent.replace(/\s+/g, '').toLowerCase();
                hrefname = this.getAttribute('href');
                id = Number(this.id);
                console.log("New Name",  linkname+"-"+hrefname+"-"+(Number(id)+1));
      })
 }
Fred
  • 35
  • 1
  • 5