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
  • 437
  • 1
  • 6
  • 19
  • 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

2

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,476
  • 8
  • 53
  • 87
  • 1
    Thank you for your help. I tried this method but it seems it will select both cases, since in the second case, `a` is still the only child of `p`. – seismatica Feb 03 '20 at 04:31
  • I tested - https://codepen.io/srikanthps/pen/Exaqoew - it seems to do what you asked for in your query. – Wand Maker Feb 03 '20 at 04:47
  • @WandMaker It doesn't, try adding this 2 codes `

    Some text

    ` and `

    test Some text

    `. You'll notice both `a` becomes red.
    – Gosi Feb 03 '20 at 05:14
  • Would be nice if you'd add some explanation about the code – U13-Forward Feb 03 '20 at 05:16
  • I tried your code on jsfiddle. It didn't work, but yes on your codepen it works. I am confused. Haha – Gosi Feb 03 '20 at 05:17
  • Thank you @WandMaker. This sadly doesn't seem to work with [BeautifulSoup](https://i.imgur.com/hD6rO2N.png), however. – seismatica Feb 03 '20 at 06:16
  • 1. OP is right, the `codepen` result is malformed, cuz there are many incompleted tags ` a:only-child)` (but this still wont work as OP expected) \ 1. I dont think what OP trying to achieve (-- by using css to detect text (/textNode) inside an element) is possible (in most browsers). May need to use Javascript. \ 1. Try **`p:has(> a:only-child:-moz-last-node:-moz-first-node)`** in mozilla, this should work. – Nor.Z Mar 16 '23 at 09:45