Question

I've been using HTML for a long time and never really had to do/tried something like this. I have an anchor tag inside a paragraph tag, like so:

<p>Hello <a href="path/page.html">World</a></p>

I was wondering if there is a way to change the style the p element if a has already been visited, using nothing but CSS. I know JavaScript can do this and by any means feel free to post a Vanilla JS answer if you will for reference, but my question really is about how to do it using just CSS.

Since I predict someone will say something like "Is the parent tag really necessary?", I know HTML5 and CSS3 brought whole new ways to style and manipulate content without the need for extra tags, but that's not the point of the question. The point is of how to do it if one ever needs to (and in my case, I do).

Was it helpful?

Solution

There are a couple of issues at play here.

  1. You can't do this with pure CSS because currently their is no parent selector. As Hashem noted above, it is currently included in the working draft for CSS4.
  2. Questions such as this suggest that it might be possible using JavaScript, to check the colour of the link for example, and deduce from that, that the link is visited. However, I've just tried on Firefox 27, and it no longer works for me. I'd speculate that it's seen as a security issue, seeing as you could potentially exploit it to work out a user's particular internet history.

Initially I suggested looking at using the ::before selector to try to achieve something, but after a little digging I came across this article (and this answer from SO) which might make for an interested read.

See this JSFiddle (updated to native JS) for my workings. It's worth noting I did try the native JavaScript check as mentioned in the above answer, as well as using the :visited selector in jQuery, but neither worked.

JS

var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i ++) {
    var anchor = anchors[i];
    console.log(document.defaultView.getComputedStyle(anchor, null).getPropertyValue('color'));       
}

HTML

<p>
    <a href="http://google.com">Google</a>
</p>
<p>
    <a href="http://nowayjose.com">Never visited</a>
</p>

CSS

a { color: #00FF00; }
a:visited { color: #FF0000; }

The potential security implications of how the ! selector in CSS4 would play out with :visited rules are pretty interesting, given that you could style a different element and then potentially query that element for a style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top