Empty elements

📺 You can watch this recipe explained in the video Empty And Non-empty Elements On The Pageopen in new window

No children

Let's use CSS selector :empty to find empty DIV elements


We have 6 HTML elements.

cy.get('*').should('have.length', 6)
cy.get(':empty').should('have.length', 2)

Let's find non-empty DIV elements

cy.get(':not(:empty)').should('have.length', 4)

Empty child

Even if there is a single empty child element, the element is not empty. For example, in the HTML below, the parent DIV in the <div><span></span></div> is NOT empty, while the SPAN is empty.


We have 7 elements.

cy.get('*').should('have.length', 7)

The SPAN and the last DIV elements are empty

cy.get(':empty').should('have.length', 2)

All other elements are not empty

cy.get(':not(:empty)').should('have.length', 5)

Empty element assertion

An element without children can checked in two ways:

<div id="me"></div>
  // an element without children
  // also matches CSS selector ":empty"
  .and('match', ':empty')

Whitespace with self-closing child

Notice that even though the parent element has no children (the child element is removed), it is still not empty.

<div id="parent"><div id="child" /></div>

The removed child element leaves empty space inside the parent HTML element.

Empty element still has whitespace

Instead of checking completely empty element we can check its properties:

cy.get('#parent').should('have.prop', 'childElementCount', 0)
cy.get('#parent').should('have.prop', 'innerText', '')

Whitespace with closing tag child

This child element has the explicit closing tag <div id="child"></div>

<div id="parent"><div id="child"></div></div>

Removing this element leaves no whitespace in the parent element.

  .and('have.prop', 'childElementCount', 0)
  .and('have.prop', 'innerText', '')

See also