2

How can I select an element, say <p>, that only contains another element, say <a>, inside it, and nothing else, like this: <p><a>Some text</a></p>? In contrast, I don't want to select things like <p>Some other text<a>Some text</a></p>, since there are stuff outside the <a> element.

I tried the CSS selector p:has(a), but this selects both of the cases above. Is there a CSS selector that only selects the first case and not the undesirable second case? Thank you.

For reference, I'm using Soup Sieve's CSS selectors.

seismatica
  • 427
  • 1
  • 6
  • 17
  • Does this answer your question? [Can CSS detect the number of children an element has?](https://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has) – Văn Quyết Feb 03 '20 at 04:30
  • Thank you for your help. The proposed solution in the link works if there is another element outside `a`, but does not seem to work when there is only text outside `a`. – seismatica Feb 03 '20 at 04:47

1 Answers1

0

Use > to select immediate children, and :only-child to select the p element only when its the only child.

p > a:only-child {
  color: red;
}

Working example: codepen.io/srikanthps/pen/Exaqoew

Wand Maker
  • 18,008
  • 8
  • 50
  • 83