Check if a div element includes a specific class using vanilla JavaScript

Starting out with vanilla JS, so please be patient ;) Time to tackle the tic tac toe game challenge!

This is the structure of my HTML:

<div class="container">
    <div class="row">
        <div class="cel empty" id="a1">
            <p>x</p>
        </div>
        <div class="cel empty" id="a2">
            x
        </div>
        <div class="cel empty" id="a3">
            x
        </div>
    </div>
    <div class="row">
        <div class="cel empty" id="b1"> x</div>
        <div class="cel empty" id="b2"> x</div>
        <div class="cel empty" id="b3"> x</div>
    </div>
    <div class="row">
        <div class="cel empty" id="c1"> x</div>
        <div class="cel empty" id="c2"> x</div>
        <div class="cel empty" id="c3">x </div>
    </div>
</div>

And here's the JS code snippet:

var fieldEmptyElements = document.querySelectorAll('div.cel');//selecting divs with the 'empty' class

    window.addEventListener('load', checkHowManyEmpty);//calling the function checkHowManyEmpty on page load


    //function to count number of empty elements with class 'empty'
    function checkHowManyEmpty(){
        for(var i=0, max=fieldEmptyElements.length; i<max; i++){
            if(fieldEmptyElements.classList.contains('empty')){
                alert('There is one element with the empty class');
            }
            else{
                alert('No element with the empty class');
            }
        }
    }

The goal was to detect if any element has the class 'EMPTY', but I encountered an error: "Uncaught TypeError: Cannot read property 'contains' of undefined at checkHowManyEmpty". Any thoughts on why this might be happening?

Answer №1

Why bother manually checking in a loop when you can let the selector engine handle it for you? It's optimized for that purpose, after all...

document.querySelectorAll('div.cel.empty').length
will quickly determine if there are any elements with the empty class among the div.cell elements.

In this improved function example from the comments, we've simplified the unnecessary else-if statement with a straightforward else:

function checkHowManyEmpty() {
    var fieldEmptyElements = document.querySelectorAll('div.cel.empty');
    if (fieldEmptyElements.length >= 1) {
        console.log('at least one element');
    } else {
        console.log('no empty elements');
    }
}

Answer №2

It appears that what you intended to do is this: (Make sure to retrieve the current index from the collection)

// ...
if (fieldEmptyElements[i].classList.contains('empty')) {
// ...

Answer №3

fieldEmptyElements is actually an array that contains multiple items. In order to access a specific item within the array, you must use the index value which in this case is represented by the variable i. As the loop continues to iterate, the value of i incrementally increases by 1.

if (fieldEmptyElements[i].classList.contains('empty'))

By following this code snippet, you are effectively retrieving the item located at the current index position within the array.

Answer №4

When using document.querySelectorAll(), keep in mind that it returns a node list. Rather than directly accessing the classList property of the node list, you should iterate through each element within the list and then check its classList.

To accomplish this, utilize a for loop where your variable i serves as the index for the node list:

fieldEmptyElements[i].classList

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the functionality of arrays within Selenium IDE

Recently delving into Selenium IDE, I am a beginner and looking for guidance. The challenge at hand: How can I access values from an array generated by execute script | var array1 = document.getElementsByClassName("Post"); return array1; | array1 Initi ...

Tips for expanding the HTTP header size within Next.js

Can someone provide assistance for increasing the HTTP header size in my Next.js app? The current size is set at 16384 and I am unable to execute the necessary command node --max-HTTP-header-size=24576 server.js. Looking for help from someone with more e ...

Tips for deleting the final separator in a list within the Material UI Grid system

Utilizing the grid system in Material UI, I have created a list of statements with dividers. However, I am seeking assistance in removing the very last divider from the list. return ( <Grid key={index}> <Grid style={{ display: 'flex ...

Dynamic URL behavior in AngularJS

Let's say I have 3 links displayed on my webpage: A B C, When the user clicks on link A, it should trigger a function like this: var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.ge ...

Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, ...

Move the footer to the bottom of the page

Is there a way to position my footer at the bottom of the screen and make it extend to the full width in a responsive manner? https://i.sstatic.net/19lSB.jpg Custom CSS for Footer: * { margin: 0; } html, body { height: 100%; } .page-wrap { min-heig ...

Issue with EmberJs: The #each loop is failing to recognize the array that was declared within the component

I'm struggling with this seemingly simple issue, and I could really use some assistance. In the JavaScript file of the component - weekShorts: computed(function() { return new Array('S', 'M', 'T', 'W', &apo ...

Can the Cross-Origin Resource Sharing issue be resolved on the client side?

I am currently developing an application that uses a REST API. The API gives me the data I need, but the browser is blocking it due to CORS policy. I have tried using some Node.js packages like cors-anywhere, but I'm still facing issues. Is it possibl ...

NodeJS domain error handling failing to catch ReferenceError exceptions

I'm currently facing some challenges with domains in NodeJS. I've set up middleware functions to wrap every call in my web application within a domain in order to capture errors, process them, and return informative error messages. While this se ...

Ensure that the image remains positioned at the bottom of the page

Although it may seem like a repetitive question, the answers I have come across are quite unbelievable. Why would multiple lines of code be needed for such a simple task? It just doesn't make sense. I specifically want to ensure that the img is locat ...

Make sure to wait for the loop to complete before moving on to the next line

I am currently leveraging the capabilities of the GitHub API to fetch a list of repositories. Subsequently, I iterate over each repository and initiate another HTTP request to obtain the most recent commit date. How can I orchestrate the iteration process ...

Using v-bind:class in Vue.js does not successfully assign a value in the method

Why is the width of my div not changing when I try to bind it to a data attribute that ranges from 0 to 100? <div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app&ap ...

Differentiating the background color of the active tab in Bootstrap while keeping other active classes unaffected

I am currently working with Bootstrap and have created a list as shown below: https://i.sstatic.net/PqBip.png The active state of this list item is blue, but I would like to change it to green or another color. Here is the code snippet: <a class="l ...

Retrieve the values of a function using the Firebase database

Hey, I'm in a bit of a pickle trying to retrieve the values returned by my function. I can see them just fine in the console log, but how do I actually access them when calling the function? function getprofile(useruid) { return firebase.database ...

Enhancing the efficiency of a Puppeteer web scraping operation

app.get("/home", async (req, res) => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); const pageNumber = req.query.page || 1; await page.goto(`https://gogoanimehd.io/?page=${pageNumber ...

Issue with the alignment of form input fields and buttons in Mozilla Firefox

Fixing Form Field Alignment Issue in Firefox After encountering and solving a form field alignment issue myself, I realized that the problem persisted in Firefox while displaying correctly in Chrome. Here's how I resolved it, although I am open to mo ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

Is it possible to access a file on the client's PC without transferring the file to the server?

Is there a way to read an excel file directly from a user's PC in a web app and insert the cell values into a MySQL database cell by cell? Or should the file be uploaded to the server first before being read? (The web app is built using JSP) ...

Tips on leveraging JQuery's $.when for handling ajax requests sequentially

How can I effectively use $.when in JQuery with chained promises to ensure my ajax requests are processed in the correct order? I have a dynamic array called costArray containing various objects. For each item in this array, I initiate an Ajax request nam ...

Using Axios for Multiple Layers of API Requests within React

I have scoured numerous forums and articles, but the code still refuses to work as expected. While I am able to log the proper data, setting the State results in an empty object for some reason. After spending hours on this, it is entirely possible that I ...