I am unable to retrieve the values from a manually created JavaScript list using querySelectorAll()

  const myList = document.createElement("div");
        myList.setAttribute('id', 'name');
        const list1 = document.createElement("ul");
         const item1 = document.createElement("li");
            let value1 = document.createTextNode("america");
            item1.appendChild(value1);
         const item2 = document.createElement("li");
                 let value2 = document.createTextNode("london");
            item2.appendChild(value2);
            list1.appendChild(item1);
            list1.appendChild(item2);
            myList.appendChild(list1);

Upon entering let li = document.querySelectorAll("#name li");

I can't seem to retrieve the list element with the li tag. What could be causing this issue in the code?

Answer №1

Instead of making that call, try this:

List.querySelectorAll("#name li");
//even better
List.querySelectorAll("li");
//since you already have the handle for #name element.

Whether they are appended to the document or not, you will still retrieve the elements from the query.

Avoid calling for the document Element on query selectors if you already have the root node of your query subjects or a local wrapper unique ID available.

It can be costly!

Always strive to avoid it.

Avoid using querySelectorAll unless absolutely necessary.

List.getElementsByTagName("li"); 

This is generally a better and faster approach to take.

Answer №2

To properly incorporate the List node you've generated into the document, follow these steps:

let List = document.createElement("div");
List.setAttribute('id', 'test');
let List1 = document.createElement("ul");
let List2 = document.createElement("li");
let Value = document.createTextNode("java");
List2.appendChild(Value);
let List3 = document.createElement("li");
Value = document.createTextNode("ajax");
List3.appendChild(Value);
List1.appendChild(List2);
List1.appendChild(List3);
List.appendChild(List1);

document.body.appendChild(List);

After executing the above code snippet, your document.querySelectorAll statement should function correctly.

Answer №3

It appears that the reason for this issue is due to the absence of List being added to the document.

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 Directories with asp.net and C# to Find Folders

.aspx file: <%@ Import Namespace="System.IO" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Explorer</title> </head> <body> <form id="form1" runat="server"> </form& ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

What is the technique for hiding the bottom tab navigator upon leaving a specific screen in React Native version 5?

In the home screen, I want only the bottom tab navigator to be visible, and then hidden until the user returns to the home screen. The example provided below is tailored for working in the App.js file, but my situation is different. const Tab = createBot ...

An animation triggered by scrolling using the @keyframes rule

Is it possible to smoothly animate a variable font using @keyframes on scroll and have it complete the animation loop when the user stops scrolling, rather than snapping back to the starting position? I've managed to make the animation work, but it l ...

Node Selenium for Importing Excel Files---I will help you

My current challenge involves using node selenium in Firefox to click a link that triggers the download of an excel file. I want the downloaded file to be saved in a specific directory, but when I click the link, a dialog box pops up giving me the option ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

How to easily open a search page with just a click on the search field in CodeIgniter?

I am in the process of implementing a search feature in CodeIgniter. My view file is divided into two main sections: Header section, which includes the search bar <?php echo form_open('controller/live_search');?> <div class="toolba ...

Troubleshooting Socket-io Client Problem After Migrating to TypeScript

I am currently in the process of migrating my MERN stack + Socket.io template to Typescript. However, I am encountering some issues specifically when transitioning the client code to Typescript. The Problem: My socket pings from socket.io-client are faili ...

Joi validation that focuses on required array elements while disregarding nested keys

Why is my Joi array required validation not detecting an empty array? I have an array called userData that contains objects with keys dateMilli and value. Despite adding required validations everywhere, passing an empty array [] for userData does not resul ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

Encountering an issue with Google distance matrix where property 'text' is undefined

Below is a snippet of code that calculates the distance between two user-provided addresses. This code currently runs when the user submits a form in this manner: $("#distance_form").submit(function (e) { e.preventDefault(); calculateDistance(); }); ...

After the state loads in Ui-router, how can I execute a function?

Transitioning from jQuery to Angular, I am struggling with ui-router and states. In jQuery, I can make an AJAX call and then run another function on success. How can this be achieved in Angular? For instance, consider the code snippet below: var ivApp = ...

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

`how to extract the href attribute value from the hyperlink that triggered a modal in jQuery UI`

Recently, I began diving into Jquery and javascript coding. As a beginner, it feels odd to refer to myself as a noob due to my age. Here's the scenario: I have a hyperlink that triggers a dialogue box and sets a cookie. The dialog asks the user, "Are ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

seeking a way to integrate Amazon information into a PHP form

Trying to fix my old system for integrating Amazon search results into a form has been quite the challenge. Originally, I had a PHP-based form where users inputted an ISBN, triggering a JavaScript program to generate a signed request that returned XML data ...

The benefits of installing gulp plugins locally versus globally

Being a newcomer to Gulp, I have a query: should I install gulp plugins (like gulp-sass or gulp-imagemin) locally or globally? Most online examples suggest installing them locally using the --save-dev option. This method saves the modules in the local node ...

`The server fails to retrieve parameters passed through an angularJS HTTP GET request,

In my controller.js file, I've come across the following block of code: $http({ method: 'GET', url: '/getGuestList', params: {exhibitorID: 1} }) The purpose of this code is to fetch all the guests belonging to a parti ...