Search code examples
javascriptif-statementnodelist

How to check if a nodelist has an element with no content in it?


I want my function to check if there is an element with no content in it first, then if the condition is true- execute the code, else don't run the function. I just don't know how to check whether there is an element with no content in it.

function randomBlock(){
    let random = Math.floor(Math.random() * blocks.length)
    if(blocks[random].textContent == ""){
        blocks[random].textContent = "O"
    } else{
        randomBlock()
    } 
}

Solution

  • Filter the NodeList to just the empty ones, then select a random element. After filtering, you can check whether there are any empty blocks available.

    function randomBlock() {
        let emptyBlocks = [...blocks].filter(block => block.textContent.trim() == "");
        if (emptyBlocks.length > 0) {
            let random = Math.floor(Math.random() * emptyBlocks.length);
            emptyBlocks[random].textContent = "O";
        } else {
            console.log("No empty blocks left");
        }
    }