Re: Select elements based on text content

On 30 March 2010 15:26, Boris Zbarsky <bzbarsky@mit.edu> wrote:

Now consider td:contains("something").  Any time a node is added to the DOM,
> one needs to check whether it has an ancestor "td" and if so whether it has
> any descendants containing the text "something" (or some variant thereof,
> depending on whether "something" can span element boundaries).  Or check
> just one of those, of course. Or check neither and restyle the entire
> document.
>
> And if you have a selector like |td:contains("something") span| then on any
> DOM insertion you have to either restyle everything under all "td"s or
> restyle all spans under all "td"s or determine whether the new node has an
> ancestor "td" (possibly more than one!) and descendant "something" and then
> restyle all "span"s under the "td"s involved.
>

I had only been considering childless nodes, for some reason (probably due
to the nature of the markup which triggered this enquiry). While one might
argue against introducing a selector that is only applicable to childless
nodes on the grounds of this being an arbitrary limitation, doing so would
go some way to solving the problems quoted above.

If we were to accept that the selector would only match childless nodes, the
procedure for restyling elements upon DOM node insertion would be
simplified. The only extra task would be to unapply any styling of the
parent node dependent on the text content selector (as the parent is no
longer a childless node).

    p:contains("day") { color: red; }

    <p>day</p>

DOM node inserted dynamically…

    <p><span>Sun</span>day</p>

The p element is no longer childless, so text content selectors no longer
match it.

As well as avoiding the need to go "up" the DOM more than one generation, we
also avoid the need to inspect the text content of nodes inserted
dynamically.

    p:contains("Sunday") { color: red; }

    <p>day</p>

DOM node inserted dynamically…

    <p><span>Sun</span>day</p>

There's no need to inspect the text content of the inserted span element.

Dynamic removal of DOM nodes would require similar treatment. Each time a
DOM node is removed, the browser would need to determine whether the parent
node is now childless, and apply styling as appropriate.

David

Received on Tuesday, 30 March 2010 03:25:03 UTC