Exploring the DOM, store all anchor elements inside a <ul> tag with a specific ID in an array

I'm attempting to extract all the anchor tags from a list and store them in an array by traversing the DOM. So far, I have been successful in getting the list items and their inner HTML into an array, but I am facing difficulties in retrieving each LI's anchor tag. The lines that are causing issues have been commented out.

<ul id="menu-list">
<li><a href="#">List Item 1</a></li>
<li><a href="#">List Item 2</a></li>
<li><a href="#">List Item 3</a></li>
<li><a href="#">List Item 4</a></li>                        
</ul>

<script type="text/javascript">
var list = document.getElementById('menu-list');
var listItems = list.getElementsByTagName('li'); //works
var listItemAnchors = listItems.firstChild //not working OR....
var listItemAnchors = listItems.childNode[0] //not working

var menuListItems = [];
for (i = 0; i < listItemAnchors.length; i++) {
    var arrValue = listItemsAnchors[i]
    menuListItems.push(arrValue);
    alert('item added');
}
</script>

Answer №1

Exploring alternatives to using getElementsByTagName:

const anchorElements = document.querySelectorAll('a');

Discover more here: http://example.com

Answer №2

Your issue lies here:

var listItemAnchors = listItems.firstChild //not functioning OR....
var listItemAnchors = listItems.childNode[0] //not working

getElementsByTagName() retrieves a collection, therefore listItemAnchors constitutes a group of elements (similar to an array structure, could either be an HTMLCollection or NodeList) and lacks the property firstChild (or any other Element properties). You need to iterate through all your listItems, or follow @Cherniv's advice and directly fetch the anchors from list.

If you wish to solely retrieve the first anchor from each li, give this a go. Otherwise, @Cherniv's solution is the optimal approach;

var list = document.getElementById('menu-list');
var listItems = list.getElementsByTagName('li');
var listItemAnchors = [];

var potentialAnchor;
//for each list item
for (var index = 0; index < listItems.length; ++index) {
    potentialAnchor = listItems[index].children[0];

    //check if it's an anchor
    if (potentialAnchor.tagName.toLowerCase() == 'a')
        listItemAnchors.push(potentialAnchor);
}

console.log(listItemAnchors);

Answer №3

arrayOne=[];
var items = document.getElementsByTagName('a');
for (var j = 0; j < items.length; j++) {
    arrayOne.push(items[j].innerText)
}

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

Issue with scrollTop not functioning when using onclick on an <a> tag within a div

After various attempts and research online, I am still experiencing erratic scrolling behavior with the scrollTop function. My goal is to scroll within a specific div when clicking on links. The content of my div: <div id="test" style="height:400px; o ...

Incorporating z-index into weekly rows within the FullCalendar interface

I'm facing an issue where my detail dropdowns on events are being cropped by the following row. Is there a solution to adjust the z-index of each week row (.fc-row) in the monthly view, arranging them in descending order? For example, setting the z-i ...

Executing the Npm audit fix --force command will automatically implement its own suggestions

Despite coming across countless similar questions, none of them have been helpful in addressing my issue. I am working on resolving critical vulnerabilities. I have executed npm update, npm audit fix, and npm audit fix --force multiple times, but the prob ...

Is there a way to transfer a component as a prop to another component in React?

Just began my journey with React and coming from a Java background, please bear with me if the way I phrase this question is not quite right. I'm interested in "passing" an instance of a component to another component (which will then use that passed ...

Troubleshooting auth error with Android and nativescript-plugin-firebase

I am currently utilizing this plugin in my application: https://github.com/EddyVerbruggen/nativescript-plugin-firebase Unfortunately, when using my real device on a 3G network, I encounter the following error: auth/network-request-failed Thrown if a netw ...

Exploring ways to customize the input color of Material UI TextField when it is disabled [Version: 5.0.8]

I am having trouble changing the border color and text color when an input is disabled. I have tried multiple variations, as seen below: const textFieldStyle = { '& label': { color: darkMode?'#1976d2':'', } ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Step-by-step guide on replacing Express API routes with React Router

I am currently working on an application that utilizes React Routes and is served with an Express server. The Express server also contains routes for API calls. Server.js const express = require('express') const path = require('path') ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Updating the component following an API request in ReactJS

I'm currently working on a component that allows users to search for friends by entering their email address. The interface consists of an input form where users can submit the email and I want to display the friend's information below the form a ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

The Challenge of the Universe's Origin

While watching the latest episode of The Big Bang Theory (Season 11, Episode 20), I found myself intrigued by Dr. Wolcott's unusual encryption method. In a quirky twist, this nutty theoretical cosmologist wrote his notes backward and converted all let ...

Revamp the current webpage to display attribute values in textual format

As I peruse a webpage, I notice that there is room for improvement in terms of user-friendliness. The page is filled with a list of movie titles, each accompanied by a link to IMDb. However, the IMDB user rating is only visible when hovering over the titl ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

The method to eliminate the default active class using AngularJS when clicking on different links

Here is the scenario: The first link is initially active and highlighted with the active class when the page loads. <a class="button active" ng-click="$parent.Filter = ''" ng-class="{ 'active': Filter === '' }"> Test l ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

Guide on retrieving the mouse button press from a command event using XUL

There appears to be a difference between the XUL command and click events. While my function is called when using the command event, the event object does not include the button property. I'm trying to figure out: how can I determine which mouse but ...

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...