Search code examples
javascripthtmlcssperformancedom

How to check if a HTML document is empty via JavaScript without causing layout/reflow?


Need to check if an HTML div is empty and contains no text and no child elements as such inside it - a black page only.

e.g

function isPageEmpty(page) {
    const paragraphNodes = page.querySelectorAll(".paragraph");
    if ((paragraphNodes[0].children[0]).innerText !== "") {
      return false;
    }

    return true;
}

What would be the best way to do it, current code causing re calculation of styles?

Accessing the innerText is causing forced re-calculation of styling.

Above code snippet is not complete as it is just to indicate what wanted to achieve.

Open for suggestion and new ideas.


Solution

  • The easiest way to check if an element is empty (no text or child elements without text) is to use !element.textContent.trim().length.
    The trim() function will also ensure that spaces are not considered as content either.

    const ELEMENTS = document.querySelectorAll('p');
    
    ELEMENTS.forEach(element => {
      element.classList.toggle('border-red', !element.textContent.trim().length);
    });
    .border-red {
      border: 2px dashed red;
    }
    <h2>Element with content</h2>
    <p>Content</p>
    
    <h2>Element with content inside child element</h2>
    <p><span>Content</span></p>
    
    <h2>Empty element</h2>
    <p></p>
    
    <h2>Elements with only empty child elements</h2>
    <p><span></span></p>