0



As depicted in the above image, I am trying to put a tick mark (✓) next to 'a set of particular' visited links (links inside li tags) in my webpage.

JS used in the HTML to insert a 'visited' attribute to <a> tags. I placed this code in the footer (after the links are displayed in the screen). This is not working though (I am not seeing the attribute created in the HTML).

localStorage.setItem('visited-'+window.location.pathname,true);
var links = document.querySelectorAll('#the-content > ul > li > a');
for (i=0;i<links.length;i++) {   
  var link = links[i];
  if (link.host == window.location.host && localStorage.getItem('visited-' + link.pathname + '/')) {
    link.dataset.visited=true;
  }
}

CSS Code
I can confirm that this code is working as if I manually create an attribute for the <a> tag, the styling is applied.

article .the-content a[data-visited] {
  border-bottom: 1px dashed orange;
}

article .the-content a[data-visited]:after {
  content: ' ✓';
}
amitz27
  • 59
  • 1
  • 2
  • 8

2 Answers2

2

Use setAttribute():

link.dataset.visited=true;
link.setAttribute('data-visited', 'true');

The dataset property only manipulates the JavaScript properties but does not impact HTML attributes. More information about the difference can be found in this question: What is the difference between properties and attributes in HTML?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
1

You can use createAttribute() for this

just replace

link.dataset.visited=true;

with

let attr = document.createAttribute("data-visited"); // Create a "data-visited" attribute
attr.value = true; // Set the value of the attribute
link.setAttributeNode(attr); // assign attribute node to element

to know more about createAttribute() check this

Update: your 'the-content' used in html is a class not an id Also replace

document.querySelectorAll("#the-content > ul > li > a");

with

document.querySelectorAll(".the-content > ul > li > a");
Hemant
  • 1,127
  • 1
  • 10
  • 18
  • Thanks for the pointer. But not working for me yet. – amitz27 Jan 10 '21 at 06:13
  • Thanks @Hemant Malik - I assume your last line of code should be "link.setAttributeNode(attr);". I updated the querySelectorAll as mentioned and still no luck. – amitz27 Jan 10 '21 at 06:23
  • The + '/' in my code caused the issue. Thanks so much for your help! – amitz27 Jan 10 '21 at 06:42
  • Great! thanks for pointing out that 'attr' issue in the code, i have fixed it now just in case someone copies it. – Hemant Jan 10 '21 at 06:45