Tips for storing dynamic data in an array using JavaScript

I'm trying to create a loop that will retrieve the href values from certain elements and store them in an array. Can someone help me with this?

var linksArray = [];
var elements = document.getElementsByClassName("title");

for (var i = 0; i < elements.length; i++) {
    linksArray.push(elements[i].href);
}

Appreciate any assistance. Thanks!

Answer №1

Utilize the Array.prototype.push() method.

let items = document.querySelectorAll(".name");
let list = [];

for (let j = 0; j < items.length; j++) {
    list.push(items[j].textContent);
}

Answer №2

To iterate over elements, you can use the foreach method as shown in this code snippet:

let items = document.querySelectorAll(".item");
let list = [];

items.forEach(function(item){
    list.push(item.textContent);
});

If you prefer using jQuery, here is how you can achieve the same result:

let items = $(".item");
let list = [];

items.each(function(index, element){
    list.push($(element).text());
});

Answer №3

Utilize an Array.

var items = document.getElementsByClassName("title");
var array = new Array();
for (var j = 0; j < items.length; j++) {
    array.push(items[j].href);
}

console.log(array);
<a class="title" href="test1"></a>
<a class="title" href="test2"></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

Sending data through forms

I'm having trouble storing values input through a dropdown menu in variables event1 and event2, despite trying global declarations. How can I successfully store a value to both variables and pass it to the JavaScript code? Thank you. <!DOCTYPE HT ...

Is it possible to specify the database connection to use in npm by setting an environment variable?

I have established a database connection in a JavaScript file. const dbCredentials = { user: 'something', host: 'localhost', database: 'something', password: 'something', port: 1111, }; export default d ...

Method for setting a BigDecimal Array

I am struggling to create a setter method for a BigDecimal array. I am having difficulty assigning a proper value to it. My goal is to have my array include at least one "zero" element or be empty in the meantime. public void setAddends(BigDecimal adden ...

How come my effort to evade quotation marks in JSON isn't successful?

When trying to parse a JSON-string using the JQuery.parseJSON function, I encountered an error message that read: Uncaught SyntaxError: Unexpected token R. This was unusual as the only uppercase 'R' in my JSON-formatted string appeared right afte ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

How to load a text file into a C++ array

I am attempting to input 20 names from a text file into an array of strings and then display each name on the screen. string creatures[20]; ifstream dataFromFile; dataFromFile.open("names.txt"); for (int i=0; i < creatures->size(); i++){ dataFro ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Updating pages dynamically using AJAX

There's a glitch I can't seem to shake off. I've successfully implemented AJAX for page loading, but an issue persists. When I navigate to another page after the initial load, the new page contains duplicate tags like <head> and <f ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

What is the best way to delete an item from a React array state?

In my Firebase database, I have an array stored under the root branch called Rooms. Within the app, there is a state named rooms which is also an array. I successfully set it up so that when a user enters a new room name and submits it, it gets added to th ...

In what way can an item be "chosen" to initiate a certain action?

For example, imagine having two containers positioned on the left and right side. The left container contains content that, when selected, displays items on the right side. One solution could involve hiding elements using JavaScript with display: none/in ...

Error encountered in Express middleware: Attempting to write private member #nextId to an object that was not declared in its class

Currently, I am in the process of developing a custom logger for my express JS application and encountering an issue. The error message TypeError: Cannot write private member #nextId to an object whose class did not declare it is appearing within my middle ...

Encountering a problem with configuring webpack's CommonsChunkPlugin for multiple entry points

entry: { page1: '~/page1', page2: '~/page2', page3: '~/page3', lib: ['date-fns', 'lodash'], vendor: ['vue', 'vuex', 'vue-router'] }, new webpack.optimize.C ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Combining Server-Side HTML with React Components and Functions: A Guide

Utilizing Vue makes it simple for me to incorporate a Vue application as a container above the server-side rendering HTML like so: <body> <div id="appMain"> <!-- This serves as the primary element for Vue --> <!-- ...

What causes the transformation of [{"value":"tag1"} into [object Object] when it is logged?

Currently on my node.js server, the code I'm using is as follows: var tags = [{"value":"tag1"},{"value":"tag2"}]; console.log("tags: " + tags); My expectation was to see this in the console: tags: [{"value":"tag1"},{"value":"tag2"}] However, what ...

Obtaining a numpy array from the elements of a separate array (in Python)

Given an array like this [[ 430 780 1900 420][ 0 0 2272 1704]] I want to transform it into the following result: [[[ 430 780 1] [1900 420 1]] [[ 0 0 1] [2272 1704 1]]] To achieve this, I need to convert a 2D array into a 3D one, separate each s ...