Ways to retrieve the identifiers of every child node UL element within a UL container

I am struggling with a basic question related to HTML structure. Here is the code snippet I am working with:

<ul>
    <li>
        <ul class=t2 id=15>
            <li class='item'>a<span class='val'>b</span></li>
            <li class='item'>c<span class='val'>d</span></li>
            <li class='item'>e<span class='val'>f</span></li>
            <li class='item'>parameters : </li>
            <li>
                <ul class=t3 id=16>
                    <li>
                        <ul class=t4 id=17></ul>
                    </li>
                    <li>
                        <ul class=t4 id=18></ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I am trying to select all child ul nodes of the ul element with id 16 and retrieve their ids. However, I am only able to select the ul with an id of 17, not its sibling with id 18. The JavaScript code I'm using is as follows:

if (document.getElementById(this.toDelete[i]).getElementsByTagName('ul').length >= 1) {
    var tag = document.getElementById(this.toDelete[i]).getElementsByTagName('ul');
        for (var k = 0; k < tag.length; k++) {
            console.log("tag name: " + tag[k].id + " these will be pushed to Delete");
        }
}

The above logic seems flawed as it only retrieves id 17 but not 18. I suspect this is because the script is selecting the ul without an id attribute. How can I modify the code to include both ids in the output?

Any help would be greatly appreciated. Thank you.

UPDATE: Here is the full function I am working with. It involves deleting certain items based on their ids and retrieving the ids of their child ul elements. Please note that the code may need further refinement for optimal functionality.

deleteItems: function () {
    for (var i = 0; i < this.toDelete.length; i++) {
        console.log("Item to be deleted: " + this.toDelete[i]);
        for (var j = 0; j < this.items.length; j++) {
            if (this.items[j].id == this.toDelete[i]) {
                this.items[j] = ""; //this should be a slice
                if (document.getElementById(this.toDelete[i]).getElementsByTagName('ul').length >= 1) {
                    var tag = document.getElementById(this.toDelete[i]).getElementsByTagName('ul');
                    for (var k = 0; k < tag.length; k++) {
                        console.log("tag name: " + tag[k].id + " these will be pushed to Delete");
                    }
                    this.toDelete.push(document.getElementById(this.toDelete[i]).getElementsByTagName('ul')[0].id);
                    //check to see if it has those there sister nodes. 
                }
            }
        }
    }
},

Answer №1

If you utilize the children method, you can access each child node and then verify if the node found is a ul using JavaScript's nodeName. For added security, I included toLowerCase() to ensure the nodeName appears as ul rather than UL.

deletedItems();

function deletedItems() {
    var ulChildren = document.getElementById('ul16').children;                
    var childrenLength = ulChildren.length;
alert(childrenLength);    
    for(var i = 0; i < childrenLength; i++){
        if(ulChildren[i].children[0].nodeName.toLowerCase() === 'ul'){
            alert("found one, the id is: " + ulChildren[i].children[0].id);
        }
    }
}

Live Example

I have made some modifications to your HTML:

<ul>
    <li>
        <ul class=t2 id=15>
            <li class='item'>a<span class='val'>b</span></li>
            <li class='item'>c<span class='val'>d</span></li>
            <li class='item'>e<span class='val'>f</span></li>
            <li class='item'>parameters : </li>
            <li>
                <ul class="t3" id="ul16">
                    <li>
                        <ul class=t4 id="ul17"></ul>
                    </li>
                    <li>
                        <ul class="t4" id="ul18"></ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

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

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...

Attempting to Create a New User and Display the Resulting Page Using JavaScript and Handlebars Templates

I've implemented a form that allows users to input data. https://i.sstatic.net/prh11.png Once the user hits "Add User", they are successfully added to the database. However, instead of transitioning to the next page as expected, the form remains popu ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...

Steps for choosing an image and embedding it within a div element

Upon loading the site, an image is displayed with the following code: <img id="some_Image" src="some_source"> However, I am looking to avoid requesting this image again from "some_source". This is because calculating the image can be resource-inten ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

My goal is to extract the usernames of all sellers from the Poshmark webpage using a combination of JavaScript, Cheerio, and Axios

After experimenting with various methods, I've come close to the solution, but it only retrieves one of the div elements I'm looking for... Although I managed to retrieve multiple divs at one point, when I attempted to extract text using the .te ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

What is the best way to update my lowdb database directly from the frontend in a next.js application?

As a hobby programmer with experience in React and Firebase, I have recently started using Next.js. I'm curious if I can utilize it as a JSON-based database for local applications on my Raspberry Pi. I have successfully set up LowDB to access data fro ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

issue with angular directive not properly binding data

I am curious about the following code: HTML: <div class="overflow-hidden ag-center" world-data info="target"></div> js: .directive('worldData', ['$interval', function($interval) { return { scope: { ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

The D3.js text element is failing to show the output of a function

I'm having an issue with my chart where the function is being displayed instead of the actual value. How can I make sure the return value of the function is displayed instead? The temperature values are showing up correctly. Additionally, the \n ...

Utilizing Ternary Operators with User Input

In my latest project, I am developing a cutting-edge app that converts text to sound, utilizing input text from react-native-elements along with ternary operators. My main challenge now is figuring out how to validate whether the text input box is empty ...

Axios - Error: Promise Rejected - The request was unsuccessful with a 500 status code

The Axios post request in my code for adding new articles is not going through, and I am encountering an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Requ ...

Inconsistent rendering issue identified in AngularJS when updating arrays with ui-router

I'm leveraging ui-router to navigate to specific subpages in my application: var myApp = angular.module("myApp",['ui.router']); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('usergroups&apos ...

Tips on invoking a Stencil component function or method from beyond the Vue instance

Is it possible to trigger a function in a Stencil component from the parent Vue instance? For example, I would like to call the callChild() method in the Vue instance, which will then trigger the doSomething() function in the Stencil component. The main ...