Css Only Get Text [Duplicate]

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

8

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

//div[@id='information']/text()

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.

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.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest