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

<div>First</div>
<div>Second</div>
<div></div>
<div>Third</div>
<div>Fourth</div>
<div></div>

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.

<div>First</div>
<div>Second</div>
<div><span></span></div>
<div>Third</div>
<div>Fourth</div>
<div></div>

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>
cy.get('#me')
  // an element without children
  .should('be.empty')
  // 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>
document.getElementById('child').remove()
cy.get('#parent').should('not.be.empty')

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>
document.getElementById('child').remove()

Removing this element leaves no whitespace in the parent element.

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

See also