JavaScript Arrays and Their Mysterious Undefined Elements

Creating a basic HTML document with a JavaScript script can be quite simple.

...
<script type = "text/javascript"> src = "xxx.js"></script>
...

<body>
  <ul id ="pics">
    <li><a href="A.jpg">A</a></li>
    <li><a href="A.jpg">A</a></li>
    <li><a href="A.jpg">A</a></li>
  </ul>
</body>

When trying to access the pictures using JS, the code snippet looks like this:

var picspics = document.querySelectorAll("#pics ul > li > a");
alert(picspics[0]);

Instead of getting the expected array of picture elements, it returned undefined. This issue persisted even after attempts to troubleshoot by adding window.onload in the code.

In an effort to debug further, I used alert function and discovered that the array of elements was coming up as undefined. Removing the JS file and manually typing the code in the console also resulted in failure.

This problem arose when attempting to iterate over the list items and add onclick events, leading to confusion about why the variable did not contain the expected array of elements. Any insight on what went wrong would be greatly appreciated!

Thank you.

Answer №1

Your current query is

var picspics = document.querySelectorAll("#pics ul > li > a");
however, pics should actually be the ul. Please update it to:

var picspics = document.querySelectorAll("ul#pics > li > a");

Answer №2

You got the wrong selector, it should actually be:

document.querySelectorAll("#pics > li > a");

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

Using ng-checked directive with a radio button in AngularJS

Within my angular application, I have implemented a loop to iterate through a collection and display the records using input type="radio". <tr ng-repeat="account in vm.pagedAccounts.items" ng-class="{ 'highlight': (account.row ...

Initiating and pausing an Interval using a single button

I'm attempting to create a JavaScript-based chronometer that starts and stops when a single button is clicked. However, I am struggling to figure out how to properly implement the setInterval function to achieve this functionality. Below is my current ...

Creating a Schema for Group Entities (Comprising Multiple Users) in Mongoose

On my website, users have the option to join groups by entering a specific code, similar to games like 'Kahoot' or 'Psych'. For instance, I generate a unique 3-word code such as 'absent agitated alive', which users can input i ...

"Preventing the propagation of a click event on an anchor tag with

Is there a way to prevent the parent anchor from executing its href when a child element is clicked, despite using stopPropagation? Here is the markup provided: <div id="parent"> <h5>Parent</h5> <a id="childAnchor" href="https:// ...

What could be causing anime.js to malfunction when clicked in Vue.js?

After implementing the mounted() function, the animation now successfully plays when the page is updated. However, there seems to be an issue as the animation does not trigger when clicked. Even though console.log registers a click event, the animation fa ...

Using @material-ui/core/useScrollTrigger in a Next.js application: a step-by-step guide

I have been researching the Material-UI documentation for useScrollTrigger and attempting to implement it in Next.js to replicate the Elevate App Bar. https://material-ui.com/components/app-bar/#usescrolltrigger-options-trigger import React from "react"; ...

Comparing scrollIntoView and moveToElement functions

When working with Selenium WebDriver, there are two primary methods to ensure an element is within the visible area: Scrolling into view: ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); Using moveToElemen ...

What is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Sending arguments to a function

I recently made a test function: void test(double** matrix); I've been trying to pass the variable double matrix[2][2] = {{1,2},{2,3}}; to this function. However, my compiler seems to be playing tricks on me and gives me this error: cannot convert « ...

Guide on converting JSON into PHP array

Struggling to convert a JSON output into a PHP array due to nested arrays within the data. This is my first time delving into PHP and JSON, and I am facing some obstacles with the json_decode() function. Any assistance would be highly appreciated. Below i ...

Encountering a TypeError while attempting to construct and launch an IOS simulator through Cordova

Currently, I am in the process of developing an Ionic app that is designed for cross-platform functionality. Encountering an Error when attempting to build and run an IOS simulator using Cordova TypeError [ERR_INVALID_ARG_TYPE]: The "code" argum ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

What steps do I need to take to ensure the progress bar extends all the way to the end of the sn

I am currently facing a challenge where the progress bar line in my message queue does not reach the end of the message before it closes. I have included a brief video showcasing the issue along with the relevant code snippet. Any suggestions or ideas woul ...

Tips for updating nested documents in mongoose with Node.js

Hi everyone, I'm facing some challenges with updating a nested document using mongoose. flashcardDeck.updateOne({ _id: deck._id }, { $set: { flashcards[Math.floor(i/2)].side1: newFlashcardsArr[i]}}); I'm encountering errors when trying to specif ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

Using Node.js, Handlebars, and Express for template inheritance

As I embark on my Node.js learning journey, I am starting with creating simple applications to grasp the fundamentals. Recently, I wanted to implement a Django-like template structure in my projects but found myself stuck on how to achieve it. I have come ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...