Guide to Repairing Uncaught TypeError: players.setAttribute is not a recognized method?

I'm a beginner and encountered an error saying Uncaught TypeError: players.setAttribute is not a function when submitting an action. How can I solve this issue? Please share your insights.

'''

//selecting all necessary elements
const selectBox = document.querySelector(".select-box"),
selectXBnt = selectBox.querySelector(".playerx"),
selectOBnt = selectBox.querySelector(".playero"),
playBoard = document.querySelector(".playboard"),
allBox = document.querySelectorAll("Section span"),
players = document.querySelectorAll(".players");


window.onload = ()=>{//once window load
    for (let i = 0; i < allBox.length; i++) {// add onclick attribute in all avaiable section's span 
        allBox[i].setAttribute("onclick", "clickedBox(this)");
        
    }
    selectXBnt.onclick = ()=>{
        selectBox.classList.add("hide");//hide the box when click
        playBoard.classList.add("show");//show the Playboard after clicking 

    }
    selectOBnt.onclick = ()=>{
        selectBox.classList.add("hide");//hide the box when click
        playBoard.classList.add("show");//show the Playboard after clicking 
        players.setAttribute("class", "players active");
    }
    
}
let playerxIcon = "fas fa-times";// class name of fontawesome cross 
let playeroIcon = "far fa-circle";// class name of fontawesome circle
function clickedBox(element){

}

'''

view image here

Answer №1

To achieve the same result as you did with allBox, you'll need to follow a similar process:

//selecting all necessary elements
const selectBox = document.querySelector(".select-box"),
selectXBnt = selectBox.querySelector(".playerx"),
selectOBnt = selectBox.querySelector(".playero"),
playBoard = document.querySelector(".playboard"),
allBox = document.querySelectorAll("Section span"),
players = document.querySelectorAll(".players");


window.onload = ()=>{//once window loads
    for (let i = 0; i < allBox.length; i++) {// add onclick attribute in all available sections' span 
        allBox[i].setAttribute("onclick", "clickedBox(this)");
        
    }
    selectXBnt.onclick = ()=>{
        selectBox.classList.add("hide");//hide the box when clicked
        playBoard.classList.add("show");//show the Playboard after clicking 

    }
    selectOBnt.onclick = ()=>{
        selectBox.classList.add("hide");//hide the box when clicked
        playBoard.classList.add("show");//show the Playboard after clicking
        for(let i = 0; i < players.length; i++)
        {
          players[i].classList.add("active");
        }
    }
    
}
let playerxIcon = "fas fa-times";//class name of fontawesome cross 
let playeroIcon = "far fa-circle";//class name of fontawesome circle
function clickedBox(element){

}

However, there may be an issue where all players will become active instead of just one specific player.

Answer №2

current:

players = document.querySelectorAll(".players");

correct:

players = document.querySelector(".players");

When using querySelectorAll, you will get access to all its children but directly applying setAttribute won't work. You need to use querySelector on the child element to apply setAttribute.

For more information, you can check out this documentation

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

What is the process for retrieving the result of a promise at a later time?

var screencastId = 'abc' var a = youtube.get(screencastId); a.then(function(screencast) { // Great, the screencast information is now available. console.log(screencast); }); // How can I access the `screencast` variable below? connection.be ...

Exploring the Evolution of jsAjaxForm from jQuery Version 2.1.3 to Version 3.2.1

I'm in the process of upgrading to a higher version of jQuery (3.2.1) and encountering difficulties with updating the ajax file upload functionality using jsAjaxForm from jQuery v2.1.3. Is there a similar function that performs the same role as jaAjax ...

I'm curious about how to properly escape single quotes when passing a variable in a Java argument call using Karate DSL. Can you help

As part of our API project at work, I am looking to incorporate database calls into our end-to-end process. One challenge I am facing is how to handle single quotes within a variable that is passed as an argument in an assert method. I have attempted the f ...

Unable to retrieve the ZIP archive generated dynamically

I am facing an issue while attempting to generate a dynamic output from MySQL queries and create an archive. Below is the code snippet I have been working with: var async = require("async"); var mysql = require("mysql"); var express = require("express"); ...

A variety of personalized Vimeo play buttons

Recently, I stumbled upon a genius solution by Chris Coyier for creating custom Vimeo play buttons. It worked perfectly for my needs, but now I'm facing a challenge - how to make it function with multiple videos on the same page. I tried swapping out ...

Making Angular table cells interactive with clicks

My table consists of multiple rows, and I want to change the color of a cell to red when clicked. However, only one cell should be red at a time. Whenever I click on a new cell, the previously red cell should return to its original color. How can I achieve ...

How can I enhance the appearance of my custom field using CSS in Advanced Custom Fields?

Utilizing the Wordpress Advanced custom field plugin, I have successfully added a custom field to my site. Within this custom field, I have inserted images and now I am looking to center them on my page using CSS styles such as margin: 0 auto. If you&apo ...

Tracking dynamic collections in AngularJS ng-repeat using track by

I am attempting to utilize ng-repeat with the result of a function call, like this: <body ng-init='a = [1, 2, 3]'> <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div> </body> where the function f is ...

Is it possible to encode JavaScript with masked binary values?

This segment of code produces the output D. The real question is - HOW? alert([][(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![] ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

Create an Angular directive that highlights a div if any of its child inputs have focus

I've developed an Angular directive for a repetitive section containing form elements. My aim is to have the entire section highlighted whenever any input field inside it is focused. template.html <div class="col-md-12 employee-section"> <l ...

Maintaining datatype integrity in MongoDB Stitch when decrementing with update statements

Using a MongoDB Stitch function, I have two collections: communities and posts. Whenever a new document is inserted in the post collection, I need to increment the summary.postCount in the communities collection by +1. Similarly, when the status of a post ...

Adjust the background color of alternate elements

I am looking to customize the background colors of every other element within the structure provided below: <div class="dets"> <div>Simple Layout</div> <div>Few Pictures/Links</div> <div>Element Uniformity</div> ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

with every instance of an ajax request sent to a separate file

Currently, I have a forEach function that is printing the "local" column from a specific database: View image here Everything is working well up to this point, and this is the output I am getting: See result here Now, my goal is to send variables via P ...

Enhance communication system by optimizing MySQL, JavaScript, and PHP chat functionality

I have created a chat application using Javascript, PHP, and MySQL for two users. Every 3 seconds, it makes an AJAX request to a PHP file to retrieve messages from the database and update the page. Currently, the PHP query used is: SELECT * FROM tmessages ...

Directive containing tracking code script

I'm working on creating a directive to dynamically include tracking code scripts in my main page: <trackingcode trackingcodevalue="{{padCtrl.trackingnumber}}"></trackingcode> This is the directive I have set up: (function () { 'use ...

Troubleshooting problem with Vuetify's parallax fluid template

In my quest to implement a fluid template for responsive design viewports, I encountered an issue. The layout looks good on medium viewports (md) but fails to scale correctly on smaller viewports (sm or xs). This is because the height of the parallax backg ...

div with fixed position and scrollable content

I'm exploring ways to create a simple webpage layout inspired by the traditional index setup. The idea is to have a fixed header/navbar div that is 200px in height, with a second div below it containing scrollable content that fills the remaining vert ...