The function setAttribute does not work with arrays

I'm facing an issue where I need to conditionally assign an attribute to each item in an array based on a radio button value. I have been able to set the required attribute on individual items, but I'm struggling to apply it to all elements in the array at once. I have tried using forEach() but I keep getting an error message saying "item.setAttribute is not a function". My JavaScript skills are not the strongest, so I'm sure there's a simple solution that I'm overlooking.

Here is what I have attempted so far: within the forEach(function(item, i) { item.setAttribute('required', 'true'); } - which is throwing an error stating "item.setAttribute is not a function"

//assign required fields to a variable
const reqCollection = [document.getElementsByClassName("reqcheck")];
console.log(reqCollection);

document.addEventListener('DOMContentLoaded', () => {
    // on .conditional_radio-wrapper click
    document.querySelectorAll('.conditional_radio-wrapper').forEach(trigger => {
        trigger.addEventListener('click', function() {
            //assign variable for "Are you a realtor?"
            let realtorRadio = document.querySelector('input[name="realtorChoice"]:checked').value;
            //log realtorRadio
            console.log(realtorRadio);
            //assign variable for "Are you represented by a realtor?"
            let repRadio = document.querySelector('input[name="realtorRep"]:checked').value;
            console.log(repRadio);
            //assign required fields to a variable

            //if they are a realtor or represented by one
            if (realtorRadio == "Yes" || repRadio == "Yes") {
                reqCollection.forEach(function (item, i) {
                    //works
                    item[0].setAttribute('required', 'true');
                    item[1].setAttribute('required', 'true');
                    item[2].setAttribute('required', 'true');
                    //does not work
                    item.setAttribute('required', 'true');
                });
            }
            //else mark as not required
            else {
                reqCollection.forEach(function (item, i) {
                    item[0].removeAttribute('required');
                    item[1].removeAttribute('required');
                    item[2].removeAttribute('required');
                });
            }

        });
    });
});

Answer №1

The code below can be improved:

const reqCollection = [document.getElementsByClassName("reqcheck")];

Instead of creating an array within an array, you can simplify it to:

const reqCollection = document.querySelectorAll(".reqcheck");

Then you can easily loop through each item like this:

reqCollection.forEach(item => item.setAttribute('required', 'true'));

Answer №2

Make sure to properly spread the elements inside the array stored in the variable reqCollection. Currently, it only contains a single element which is a HTMLCollection returned from the getElementsByClassName method. Use the spread operator on

document.getElementsByClassName("reqcheck")
to achieve this.

const reqCollection = [...document.getElementsByClassName("reqcheck")];

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

Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message Class constructor XX cannot be invoked without 'new'. After researching online, it seems that this problem typically arises when a transpiled cla ...

Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. ...

Procedure: Calculating the median of two arrays with varying sizes

A snippet of code was copied from this source. Although I can come up with a simple algorithm for finding the median of two sorted arrays when combined, this particular code seems to be following a similar approach but I am having trouble understanding it ...

Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling. I'm working with an array of objects that have nested properties which I need to loop through and consolidate. ...

sorting a multidimensional array by multiple criteria in Ruby

My csv file contains 14 columns and I need a way to sort it in ruby based on the values in the 6th column, followed by the 2nd and then the 11th column. While the .sort_by method works well for sorting by two columns, it seems to have limitations. Even us ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

The server at localhost responds with a CANNOT GET/ error message

This is the code snippet I've been working on: const express = require('express'); const app = express(); const bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: false})); app.use(bodyparser.json()); c ...

Why is the jQuery not functioning within the AngularJS function?

I am encountering an issue with writing jQuery inside an AngularJS function. I can't seem to figure out why it's not working properly. HTML <div> <span ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showD ...

Node.js error: Headers cannot be set once they have been sent

I'm struggling with sending form data through express.js and encountering the following error: After establishing communication, it's not possible to modify headers. This is the current state of my code: app.post('/api/users/profile/:us ...

How to find the maximum product value of column combinations along with their corresponding indices in Python?

I am working with a multidimensional numpy array of size M*N, where each element is a float value between 0 and 1. For simplicity, let's take a 3*4 array as an example: a=np.array([ [0.1, 0.2, 0.3, 0.6], [0.3, 0.4, 0.8, 0.7], [0.5, 0.6, 0.2, 0.1] ]) ...

Experience running two functions simultaneously in jQuery simulation

Presented here are two functions that I am working with: loadTop(); loadBottom(); One of these functions is responsible for loading the top portion of a page while the other takes care of loading the bottom. The loadTop function involves asynchronous o ...

Working with Garber-Irish in Rails: Streamlining Administration and Keeping Code DRY

I am currently implementing the innovative garber-irish technique to organize my JavaScript files. Here's my issue: I have a Model (let's call it Item) with an init function located in app/assets/javascripts/item/item.js For example: MYAPP.ite ...

Distinguishing Between Model and View State Management in AngularJS

As I work on a complex single page application in Angular, I find myself needing to manage two types of data. First, there is the Model data which pertains to information retrieved from and sent to the backend API server. Second, there is ViewState data wh ...

Attempting to pass an array via a GET variable, only to find that when displayed, the variable is depicted as the string 'Array'

When I construct a URL like this: cart.php?action=add&p[]=29&qty[]=3&p[]=5&qty[]=13 I encounter an issue grabbing the values of the p and qty variables, where they display as 'Array'. Upon using var_dump, the result is: array( ...

What might be causing res.download to retrieve a zip file that is empty?

Using expressjs for my app development, I have created a service to download files on the client side using res.download(filepath, filename). The following is the code snippet of my service: router.route('/downloadFile').get(function(req,res){ ...

Slight Misalignment of Elements

I am attempting to align two corners of an element so that they perfectly match the corners of another element. In simpler terms, I am aiming to synchronize the corners of one element with those of another element. Below is the code snippet: ... When y ...

Encountering an error message in MongoDB, specifically the "BadValue" error, when attempting to utilize the $map aggregate function due to the

My goal is to convert an array of strings into an array of ObjectIds using the map function. The map function will generate an array of ObjectIds that I will use in $match to compare if the _id matches with any of the objectids present in the array using t ...

No acknowledgment from command

Why doesn't the bot respond when I run this command? There are no errors. Do I have the role that matches in r.id? client.on('message', async message => { // Check if the user has a role with an id if(message.author.bot) return; ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...