October 25, 2024
Chicago 12, Melborne City, USA
javascript

JavaScript – Array contains HTMLDivElements instead of textContent from the elements (numbers)


I am working on a vanilla JavaScript bingo game. I create my bingo card element, then create a grid. I create 5 arrays of 5 randomized numbers each. Then for each number in each array, I create a div element, add a class of ‘marker’ to the element, stick in the randomized number as the textContent, and append the element to the HTML. Creating the card works fine. I have also set up to mark the spaces on the cards. When a space is marked I add a class of ‘marked’ to it.

Now I am trying to return an array of the marked spaces (this is the first part of a method to check if the person has an actual bingo). I grab all of the card spaces using querySelectorAll(".marker"). I then run an Array.from filter method to pull out the spaces that contain the ‘marked’ class. Then I assign the textContent (a number) from that space (the div element) to a variable and return that variable. I have a console.log to tell me what the textContent is before I return it. When the filtering is done, I do a console.log of the array that is supposed to contain the values from the textContents of all the elements.

The problem is that instead of showing the numbers from the spaces, the final console log reads as follows:

The marked spaces are: [object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement]

The console log inside the filter shows the actual number that is the textContent, and that is what I’m returning in the filter method. So why is the array I’m saving those numbers to showing each as an HTMLDivElement instead of string/number like the inner console log?

Here is my JavaScript code:

const bingoCard = () => {
    const bingoCardSpace = document.getElementById('bingo-card');
    const cardSheet = document.createElement("main");
    cardSheet.classList.add('inline-block', 'mx-auto', 'min-w-fit', 'border-8', 'bg-[#4bb2d3]', 'border-[#4bb2de]');
    bingoCardSpace.appendChild(cardSheet);

    const cardHeader = document.createElement('header');
    cardHeader.classList.add('flex', 'rounded-xl', 'bg-[#345995ff]');
    cardSheet.appendChild(cardHeader);

    const cardLetters = ['B', 'I', 'N', 'G', 'O'];

    for (let i = 0; i < cardLetters.length; i++) {
        const headerCell = document.createElement('div');
        headerCell.textContent = cardLetters[i];
        headerCell.classList.add('w-28', 'h-28', 'font-chewy', 'text-7xl', 'flex', 'justify-center', 'items-center', 'bg-[#f5f5f4ff]','rounded-full', 'mx-2', 'my-2');
        if (i != cardLetters.length - 1) headerCell.classList.add('mr-2');
        cardHeader.appendChild(headerCell);
    }

    const card = document.createElement("div");
    card.setAttribute("id", "card");
    card.classList.add('inline-grid', 'grid-rows-5', 'grid-flow-col', 'bg-[#4bb2de]');
    cardSheet.appendChild(card);

    let cardNumbers = [];
    cardNumbers = createCardArrays();
    for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; j++) {
            const cardCell = document.createElement("div");
            let cardCellNumber = cardNumbers[i][j];
            if (i === 2 && j === 2) {
                cardCell.textContent = "FREE";
            } else {
                cardCell.textContent = cardCellNumber;
            }
            cardCell.classList.add('marker', 'w-28', 'h-28', 'font-lato', 'text-5xl', 'flex', 'justify-center', 'items-center', 'bg-[#f5f5f4ff]', 'rounded-full', 'mx-2', 'my-2', cardCellNumber);
            card.appendChild(cardCell);
        }
    }
    listenForMarkingSpaces();
}

function createCardArrays() {
    const cardNumbers = new Array(5);
    let max, min;
    for (let i = 0; i < 5; i++) {
        cardNumbers[i] = [];
        max = 15 * (i + 1);
        min = max - 14;
        cardNumbers[i] = generateRandomNumbers(5, min, max);
    }
    return cardNumbers;
}

function generateRandomNumbers(count, min, max) {
    let uniqueNumbers = new Set();
    while (uniqueNumbers.size < count) {
        uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    const uniqueNumbersArray = [...uniqueNumbers];
    return uniqueNumbersArray;
}

const bingoBalls = () => {
    const ballArray = [];
    for (let i = 1; i <= 75; i++) {
        ballArray.push(i);
    }
    return ballArray;
}

let bingoBallsNotDrawn = bingoBalls();
let bingoBallsDrawn = [];

const drawBingoBall = () => {
    let ballDrawn = 0;
    while (bingoBallsNotDrawn.indexOf(ballDrawn) === -1) {
        ballDrawn = Math.floor(Math.random() * 75) + 1;
    }
    bingoBallsNotDrawn = bingoBallsNotDrawn.filter(ball => ball !== ballDrawn);
    console.log('bingoBallsNotDrawn now has ' + bingoBallsNotDrawn.length + ' balls in it');
    if (ballDrawn >= 61) ballDrawn = 'O-' + ballDrawn;
    else if (ballDrawn >= 46) ballDrawn = 'G-' + ballDrawn;
    else if (ballDrawn >= 31) ballDrawn = 'N-' + ballDrawn;
    else if (ballDrawn >= 16) ballDrawn = 'I-' + ballDrawn;
    else ballDrawn = 'B-' + ballDrawn;
    bingoBallsDrawn.push(ballDrawn);
    showBallDrawnOnScreen(ballDrawn);
    addBallToBallsDrawnList(ballDrawn);
    console.log('bingoBallsDrawn now has ' + bingoBallsDrawn);
    console.log('bingoBallsNotDrawn: ' + bingoBallsNotDrawn);
}

const showBallDrawnOnScreen = (ballDrawn) => {
    const currentBall = document.getElementById('currentBall');
    currentBall.textContent = "";
    const currentBallNumber = document.createTextNode(ballDrawn);
    currentBall.appendChild(currentBallNumber);
}

const addBallToBallsDrawnList = (ballDrawn) => {
    const ballList = document.getElementById("accordion-content");
    const listedBall = document.createElement("div");
    listedBall.textContent = ballDrawn;
    listedBall.classList.add('text-4xl', 'text-center', 'py-2', 'px-4', 'border-r-2', 'border-l-2', 'border-b-2', 'border-[#714BDE]', 'text-[#714BDE]');
    ballList.appendChild(listedBall);
}

const listenForMarkingSpaces = () => {
    const spaces = document.querySelectorAll(".marker");
    spaces.forEach((space) => {
        space.addEventListener("click", function (evt) {
            space.classList.toggle('bg-[#f5f5f4ff]');
            space.classList.toggle('bg-[#26c485ff]');
            space.classList.toggle('marked');
        });
    });
} 

const toggleAccordion = () => {
    document.getElementById('accordion-content').classList.toggle("hidden");
    document.getElementById('arrow-icon').classList.toggle("rotate-180");
}

const startNewGame = () => {
    const ballList = document.getElementById("accordion-content");
    ballList.innerHTML = '';
    const currentBall = document.getElementById('currentBall');
    currentBall.textContent="";
    const spaces = document.querySelectorAll(".marker");
    spaces.forEach((space) => {
        space.classList.remove('bg-[#f5f5f4ff]');
        space.classList.remove('bg-[#26c485ff]');
        space.classList.remove('marked');
        space.classList.add('bg-[#f5f5f4ff]');
    });
}

const checkIfMarksAreCorrect = () => {
    const spaces = document.querySelectorAll(".marker");
    const markedSpaces = Array.from(spaces).filter((space) => {
        if (space.classList.contains('marked')) {
            console.log(space.textContent);
            spaceNumber = space.textContent;
            return spaceNumber;
        }
    });
    console.log('The marked spaces are: ' + markedSpaces);
}

And here is my HTML:

<div class="flex">
    <div class="w-3/4 h-100lvh flex flex-col border-r border-black-500" id="bingo-card">
        <div class="flex justify-center">
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="startNewGame()">New game</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="bingoCard()">Click to create card</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="drawBingoBall()">Click to draw ball</button>
            <button
                class="rounded-full text-4xl m-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE] hover:bg-[#714BDE] hover:text-gray-100 focus:outline-none"
                onclick="checkIfMarksAreCorrect()">Click to check card</button>
        </div>
    </div>
    <div class="w-1/5">
        <div class="flex mt-4 text-[#714BDE] font-bold justify-center text-4xl">
            Current ball: <span id="currentBall" class="ml-4 text-[#A14BDE]"></span>
        </div>
        <div class="overflow-hidden" onclick="toggleAccordion()">
            <div class="flex text-4xl justify-center mx-4 mt-4 py-2 px-4 border-2 border-[#714BDE] text-[#714BDE]">
                Balls drawn
                <span class="transform transition-transform" id="arrow-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                        stroke="currentColor" class="size-12">
                        <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
                    </svg>
                </span>
            </div>
            <div class="px-4 hidden" id="accordion-content">

            </div>
        </div>
    </div>
</div>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video