Skip to content

:empty pseudo-selector (spec updated) #180

@brandonmcconnell

Description

@brandonmcconnell

Description

:empty pseudo-selector (spec updated to also match elements with only whitespace)

Quoting the spec:

The :empty pseudo-class represents an element that has no children except, optionally, document white space characters. In terms of the document tree, only element nodes and content nodes (such as [DOM] text nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness; comments, processing instructions, and other nodes must not affect whether an element is considered empty or not.

Example: p:empty is a valid representation of the <p> elements in the following HTML fragment:

<p></p>
<p>
<p> </p>
<p></p>

Example: div:empty is not a valid representation of the <div> elements in the following fragment:

<div>text</div>
<div><p></p></div>
<div>&nbsp;</div>
<div><p>bla</p></div>
<div>this is not <p>:empty</p></div>

Rationale

The :empty pseudo-class is already widely supported among most modern browsers, but the spec has since changed to include matching for elements that contain only whitespace and no non-whitespace nodes or text nodes.

Quoting the amendment to this change from the spec:

Note: In Level 2 and Level 3 of Selectors, :empty did not match elements that contained only white space. This was changed so that that—given white space is largely collapsible in HTML and is therefore used for source code formatting, and especially because elements with omitted end tags are likely to absorb such white space into their DOM text contents—elements which authors perceive of as empty can be selected by this selector, as they expect.

In modern web development, we have bundlers that remove all non-whitespace characters from elements, so this is not normally an issue for a good number of us, but that limits the use of features like this to those of us running non-standard tools and further gate-keeps those without them, namely JAMstack devs who may have to ensure none of their elements are ever empty, so they can target in CSS them as expected.

It's the main reason for why we tend to see HTML like this in the wild, to ensure all elements contain no unexpected whitespace:

<div
    >Some content<span
        >some more content</span
    ></div
>

Related discussions:

Specification

https://w3c.github.io/csswg-drafts/selectors-4/#the-empty-pseudo

Tests

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions