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

I encountered a console issue that I am struggling with. It is showing the error message "TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"

When running this code, I encountered an error in the console (TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'). Can someone help me identify where I made a mistake and provide guidance ...

Guide to embedding a qr code within a pdf document

I've been working on creating a PDF file generation feature where users can download the PDF with a QR code embedded in it. While I've successfully implemented the PDF generation part, I'm facing an issue with adding the QR code to the file. ...

What is the best way to locate and list all video links, and include options for "Play Video" and "Download Video"?

I have a project where I am using PHP to crawl and generate video links from the web. Now, I am looking to implement an option for users to either "Play Video" or "Download Video" when a video link is detected, along with adding a video player if the user ...

Updating the state of a Next.JS router component with React.JS: A step-by-step guide

I've implemented a toggleswitch in my app that changes its state based on the dynamic URL parameters. For instance, if the URL includes a parameter named followType set to following (e.g. https://www.example.com/home?followType=following), I want the ...

Implement a recursive approach to dynamically generate React components on-the-fly based on a JSON input

My goal is to develop a feature similar to Wix that allows users to drag and drop widgets while adjusting their properties to create unique layouts. To achieve this, I store the widgets as nested JSON documents which I intend to use in dynamically creating ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...

Can you retrieve a reference/pointer to a specific property of an object in JavaScript?

I am looking to generate an HTML <input> element, and then access its value property so I can update the value through that reference: var input = document.createElement('input'); var valueRef = &(input.value); *valueRef = "Hello world!" ...

The iisnode encountered an issue with HRESULT 0x6d resulting in a status code of 500 and a substatus of 1013

Despite trying multiple solutions, none seemed to work for my Node.js website hosted on Windows IIS with iisnode. Everything was running smoothly until today when I encountered an interesting situation. Let's say my domain is cdn1.site.com and it&apos ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

Converting JavaScript numbers into years and months format

Given an integer, for example 20, I am trying to calculate how many months and years are represented by that number. For 20, the result would be 1 year and 8 months. How can this be achieved using JavaScript? switch (props.term) { case (props.term ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...

Why is it that one of my useQuery hooks is returning a value while the other one is returning undefined?

I'm currently facing an issue with React Query where one of my useQuery hooks is logging undefined while the other one is displaying the correct data. Both functions are async and perform similar tasks. I've been troubleshooting this problem for ...

Extract the raw text content from nested elements

Working with highlight.js to include a custom CSS code, however, this library automatically adds span tags around the desired text For example: <pre> <code class="language-css hljs" contenteditable="true" id="css-code&quo ...

Using JavaScript and node.js, make sure to wait for the response from socket.on before proceeding

My task involves retrieving information from the server on the client side. When a client first connects to the server, this is what happens: socket.on('adduser', function(username){ // miscellaneous code to set num_player and other variabl ...

Is it possible to return a promise after utilizing .then() in AngularJS?

As someone who is still getting the hang of Angular and promises, I want to make sure I'm on the right track. Right now, my data layer service uses Restangular to fetch data and returns a promise. Here's how it looks... dataStore.getUsers = fun ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

Which is the preferred method: utilizing ajax calls from assets/javascript/*.js or *.js.erb views?

I am developing an admin service on Rails that communicates with a network communicator. Here is my challenge: When a user clicks a button, they are presented with network groups to choose from. Once the user selects a group, they should be able to see th ...

After combining two files in browserify, the error message "XXX.foo is not a function" appeared

When using browserify to bundle two JavaScipt files into one with the command: browserify X1.js X2.js --standalone XXX > bundle.js The file X1.js contains a function like this: function foo() { console.log("something") } And it is being exported i ...