Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Add an attribute to <a> tag using JS



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: ' ?';
}
question from:https://stackoverflow.com/questions/65650337/add-an-attribute-to-a-tag-using-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...