0

I'm trying to find some text inside an element using a css selector, but not include the children of the element. For example:

<div id="information">
 This is the text I need
 <div>I don't want this text</div>
 <span>I also don't want this</span>
</div>

Any ideas?

NOTE: I'm parsing a page so I don't have control over the elements

Rob
  • 7,028
  • 15
  • 63
  • 95

3 Answers3

3

Apparently not possible using CSS Selectors. With XPath though, if someone is interested:

//div[@id='information']/text()
Rob
  • 7,028
  • 15
  • 63
  • 95
2

So you want the loose text inside of #information but you don't want the div and the span? Seems quite simple:

#information {
    /* property values */
}

#information > div {
    display: none; /* removes content of child div */
}

#information > span {
    display: none; /* removes content of child span */
}

I guess you don't really even have to use the child (>) selector, too.

Jace Cotton
  • 2,004
  • 1
  • 21
  • 38
  • I don't think this "gives" you that content... I mean it doesn't select or store it so that you can do something with it. I think that's what the OP wants...I could be wrong. Jace, do you have any idea how to do that - I'd like to know for myself. – Flak DiNenno Nov 23 '21 at 11:09
1

There is no CSS selector to select just the text content of an element. There is nothing illogical about the idea (CSS could have a pseudo-element for the purpose), but currently there is no specification or even draft on such matters.

What you can do is to set styles on an element and then override them on any child element, possibly using a selector like #information * that matches all descendant elements or #information > * that matches all child elements.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390