0

I'm having some trouble with my CSS selector. The goal is to style anchor <a> tags with some custom styles, but to leave it alone if it contains an icon. In the example below the icon would be the <span> tag.

I've tried lots if things with :not() selectors, but to no luck. Here's what I've got so far showing the problem:

a {
  color: red;
}

a span {
  color: unset;
}
<a href="#">styled</a>
<br>
<a href="#"><span>not styled</span></a>

The problem here is that first <a> tags are styled, and then after only the <a><span> tags are unstyled. And because in the selector the span is last, that will be where the style is applied on, not the parent <a> element.

We also can't use a selector like a * in the first part, because in the HTML there is an anchor without a child. The * would only match <a> tags with any child, not empty ones.

Maybe there is some way or trick to only match when the element has a <span> tag, but then apply the style to the <a> tag. Another valid solution to me would be matching just an empty <a> tag without children, because this would not include the <a><span> tags. I thought the :empty selector might help with that but it seems this just matches if it has no content at all, but in this example the <a> tag does have content, just no child element.

Note: Changing the HTML is not really an option because this comes from user input using a WYSIWYG editor. I would have to make a function that rewrites some parts of the HTML, which is not desirable.

I'm not sure if this is possible in CSS, but it seems like such a simple example. If anyone could help me out here that would be awesome. Thanks

J0R1AN
  • 583
  • 7
  • 10
  • Ok, this looks like the classic question of "Does CSS has a parent selector"? Yes, it does with [:has](https://developer.mozilla.org/en-US/docs/Web/CSS/:has) selector which is unsupported in most of the browsers at the moment. You can make use of JS in this scenario. Better. – m4n0 Jun 04 '22 at 09:25
  • Thanks, I had looked at this and saw that there was not much support for the `:has` selector. A small difference here is the fact that just matching an empty `` tag would also solve the problem. Is there also not a way to do this in CSS? – J0R1AN Jun 04 '22 at 09:31
  • If you have a WYSIWYG then you are running JavaScript. You didn't post a JavaScript tag. I'm 99% sure that you'll need a little bit of JavaScript. There's a way to use `:empty` but you'll need to change the way you setup your anchors. An easier way is just use a class on specific anchors. – zer00ne Jun 04 '22 at 09:31

1 Answers1

-2

Well you can do this with JavaScript

JavaScript

for (x of document.getElementsByTagName("a")) {

if (x.children[0] != undefined) {
if (x.children[0].tagName=="SPAN" || x.children[0].tagName=="span") {
x.style.color="unset";
}
}

}
Sevada 797
  • 346
  • 1
  • 8