I'm listing all of the links to the bottom of some websites with document.links
(with a userscript).
Visited and unvisited url-s are appearing together. I can set different colors to them so it is easy to see which links are new and which ones I visited already. But I'd like to see only the new links.
Is there a way to tell document.links
to list only the unvisited (new) (a:link
) links?
(If not possible, then how could I hide the visited links? I've tried visibility:hidden;
and display:none;
on a:visited
, but not working. Found out it is a privacy related thing, but I don't want to touch the links on the original page, only in my link collection which is a copy of those.)
Possibly Not Possible
I'm not entirely sure how possible that this will be due to the security issue similar to the one you mentioned in this similar article that have resulted in the :visited
selector being severely restricted, making programmatic access nearly impossible in modern browsers.
Workaround Through localStorage
I suppose that you could use a workaround similar to the one mentioned in this blog post, which uses localStorage to explicitly store the links that were clicked on and persist "visited" attributes so that you can identify those that have been touched :
function check_visited_links(){
// Access all of the elements that have been visited (from local storage)
var visited_links = JSON.parse(localStorage.getItem('visited_links')) || [];
// Iterate through your links
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var that = links[i];
// When the link is clicked, store a reference in localStorage to it
that.onclick = function () {
var clicked_url = this.href;
if (visited_links.indexOf(clicked_url)==-1) {
visited_links.push(clicked_url);
localStorage.setItem('visited_links', JSON.stringify(visited_links));
}
}
// Indicate the link was visited by setting it's class
if (visited_links.indexOf(that.href)!== -1) {
that.className += ' visited';
}
}
}
This approach would append a "visited" class to your elements and would allow you to explicitly remove them by either using a purely CSS approach :
a.visited { display: none; }
Or by using a Javascript technique similar to the one you originally used via :
document.querySelectorAll('a.visited');
Example Using localStorage
Technique
You can see an example that uses the localStorage
technique here (just reload after each button press for example purposes) and an example of its output below :