Tips for retrieving multiple div elements by their id using the querySelectorAll method

Looking to incorporate a new feature for a click event. I'm trying to hide four div elements but the code seems to be ineffective. Can you identify what's wrong with it?

<a class="lightbox-close" href="#" onclick="document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4').style.display = 'none';"></a>

Answer №1

If you use the querySelectorAll method, you will receive a NodeList that requires iteration to set the properties.

Creating a separate function for the iteration logic would be a more organized approach.

var elements = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var j = 0; j < elements.length; j++) {
    elements[j].style.display = 'none';
}

Answer №2

When it comes to query selector, it is different from a jQuery selector. In jQuery, you can select multiple elements like this:

$('#goofy_1,#goofy_2,#goofy_3,#goofy_4')// it will get you all div selected 

However, query selector returns a nodeList. This means you are actually getting

Try to log your querySelectorAll

 console.log( querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4'));

you will get something like

For example, I am selecting a

https://i.sstatic.net/J7s66.png

As you can see, there isn't a single element selected, so you cannot make direct changes.

Therefore, you need to loop through all the elements as Arun P Johny suggests

var allElements = document.querySelectorAll('#goofy_1,#goofy_2,#goofy_3,#goofy_4');
for (var i = 0; i < els.length; i++) {
    allElements [i].style.display = 'none';
}

For more information, check out this link:

Difference between HTMLCollection, NodeLists, and arrays of objects

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

In Safari, the CSS filter value may not be applied immediately, whereas in Chrome it is

While dragging the input range, the brightness value (also a CSS property) updates but the image is not instantly affected in Safari. (It works well in Chrome) How can the changes be applied to the image while dragging? var app = Vue.createApp({ data() ...

What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far. However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some err ...

Transferring TypeScript modules for browserifying

Recently, I transformed my canvas library from plain JavaScript to TypeScript. I have structured the code using classes, all of which are part of the cnvs module. However, I am facing difficulties in compiling these classes into a single file. My goal is ...

Customize TYPO3 templates by modifying the div id structure

I have a template in TYPO3 that I want to use for multiple pages. Within this template, there is a specific DIV element. I am wondering if it's possible to change the ID of the DIV based on the page UID. This DIV is the only one that changes its cont ...

AJAX request failed to elicit a response

Recently, I've been facing an issue with my AJAX call to the API. Previously, it was functioning correctly and returning a response JSON. However, now I am unable to retrieve any JSON object. When using Mozilla, no error is shown but the response JSON ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

Tips for navigating through a complex object returned from an API.integration**How to

Looking at this API response, I need to extract all the appId and userInfo values. How can I efficiently iterate through this response? { "status_code": "SUCCESS", "status": "SUCCESS", "message" ...

Ensure that the divs are properly aligned and construct columns within a single column

I've been working on creating a step bar that needs to adapt to any number of steps provided by the backend. Here's what I have so far: https://i.sstatic.net/cj4qZ.png It looks fine, but connecting the circles with bars would be beneficial. How ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData [0] object amount: 29.9 code: "012" currency: "BRL" payedDate: "2016-11-10" roDate: "2016-08-01" type:"OTHER" [1] object amount: 39.9 code: "013" currency: "BRL" payedDate: "2016-11-11" roDate: "2016- ...

Creating a Dynamic Ball Animation in JavaScript using Canvas

What should I tweak in the code to make the ball bounce upward at the beginning? I am completely lost here and have experimented with numerous ideas without success. I feel like I must be overlooking something simple. It seems like the key part of the co ...

What is the best way to use Bootstrap to position form input at the bottom of a page?

Does anyone have any tips on aligning a bootstrap form input to the bottom of the page? I've tried a few different methods but haven't had any luck. Here's how it looks currently. And here's how I'd like it to look. I'm aim ...

Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it. Here is the code snippet that I'm currently using: function followIt(e) ...

Implementing Content-Security-Policy for a web application embedded in an iframe

Hey there! I've got this cool webapp called myApp, developed using Spring Boot and Vaadin. It's going to be deployed on a Tomcat server at http://tomcatserver:8080/myApp Now, what I want to do is display the webapp in an iframe like this: <if ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...

Utilizing the designated link name

As part of my program, I have to generate hyperlinks for each row in a MySQL table. To accomplish this, I used the C MYSQL API to fetch the data from the table: while ((row = mysql_fetch_row(result))) { ....//some code to print the data.... } I am ab ...

Unable to generate a file using fs.appendFile in Node.js

For some time now, I've been working on a program that is meant to save logs from a Slack team. I've managed to get most things working, but I've hit a roadblock with using fs.appendFile() successfully. The documentation states that it shoul ...

Mobile devices consistently experiencing issues with JavaScript generated elements overlapping

I'm currently in the process of creating a quiz based on a tutorial I found at https://www.sitepoint.com/simple-javascript-quiz/. While I followed the tutorial closely and integrated Bootstrap, I am encountering an issue specifically with mobile devic ...