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
  • 408
  • 1
  • 5
  • 15
  • 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

2 Answers2

1

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
  • 17,377
  • 6
  • 43
  • 79
-1
p a {
`enter code here`
}

however i suggest adding a class to element a so it will target only the text for this part of the code since down the road in your page you might have more a wrapped inside p that you don't want those same format, thus there use a different class (or no class there)

Avinash
  • 13
  • 4