What is the best way to extract data from multiple instances of <span> tags and store them in an array?

I am in search of the most effective method for extracting multiple span tags from various spans and organizing them into an array or JSON object for future use. (I'm unsure whether an array or JSON is the optimal choice.)

HTML:

<span class="car" id=c1 data-make="volvo" data-year="2010">Car1<span>
<span class="car" id=c2 data-make="saab" data-year="1998">Car2<span>

JavaScript:

var cars = document.getElementsByClassName('car');
for(var i=0; i<cars.length; i++) { 
  <- what should be included here? ->
}

Currently, I have created three separate arrays for ID, make, and year, but it seems disorganized. I am struggling with how to create:

    Array(
[0] => Array(
        [id] => c1 
        [make] => volvo
        [year] => 2010
    )
[1] => Array(
        [id] => c2
        [make] => SAAB  
        [year] => 1998    
    )
);

Or a JSON object:

jsonString = [
    {
        "id": "c1",
        "make": "volvo",
        "year": "2010",
    },
    {
        "id": "c2",
        "make": "saab",
        "year": "1998", 
    }
];

The purpose of this is simple. I intend to use this information to replace innerHTML like so:

document.getElementById(car[id]).innerHTML = car[make]

So, two questions: 1) What would be more suitable for this task - multi-dimensional array or JSON object? 2) What should be inserted in the section of my loop to store the data in that array or JSON?

Thank you - I am still gaining knowledge.

Answer №1

To extract all the data- attributes from each element, iterate through each attribute and store them in a separate object:

var output = [],
    regExp = /^data-/;

for(var index = 0, len = elements.length; index < len; index++) { 
    var currentElement = elements[index],
        attributes = currentElement.attributes,
        dataObject = {};

    // setting the ID
    dataObject.id = currentElement.id;

    // iterating over all attributes
    for(var count = 0, attrLen = attributes.length; count < attrLen; count++) {
        var attrName = attributes[count].name;
        if(regExp.test(attrName)) { 
            // remove the 'data-' part and add the value to the object
            dataObject[attrName.replace(regExp, '')] = attributes[count].value;
        }
    }

    // adding the object to the final array
    output.push(dataObject);
}

SEE DEMO

Answer №2

For those open to utilizing jQuery, the following code can be employed. Otherwise, Felix's solution is recommended.

An array of objects should be utilized in the following manner:

let arr = [];
$("span").each(function(i) {
    arr[i] = {};
    arr[i]["id"] = $(this).attr("id");
    arr[i]["make"] = $(this).data("make");
    arr[i]["year"] = $(this).data("year");
});

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

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Display the Vaxis line in a bar graph using Google Chart

Currently, I am involved in a project where I need to display a graph that resembles the one depicted here. To accomplish this task, I am utilizing the Google Visualization Chart API. Successfully, I have managed to generate the chart as illustrated below ...

What methods can I use to gauge the performance of my angular website?

After completing my web project with nodejs and expressjs on the backend and angularjs on the frontend, I am worried about the performance implications. People say that JavaScript can be dangerous if not used correctly, so I ran jshint to verify my synta ...

Having trouble simulating JavaScript Math.random in Jest?

Math.random() seems to always return random values instead of the mocked ones. script.test.js jest.spyOn(global.Math, "random").mockReturnValue(0.123456789); const html = fs.readFileSync(path.resolve(__dirname, "./script.html"), " ...

Utilizing v-data-iterator in Vuetify to display data fetched from an API in a table

After a long day of searching and experimenting, I've finally arrived here. Initially, I attempted to create a simple table with 2 columns using Row and iterate over the object to populate the left column with its keys. However, I hit a roadblock when ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Discover the process of retrieving HTML elements from a different webpage and incorporating them into your own site

As a newcomer, I'm in search of a code that can help me fetch an HTML string from one webpage and use it in another webpage. To illustrate my point, consider the following mock examples. Example 1: Mysite.com/A.html <body> <!---My Script Goe ...

jQuery simple authentication is not functioning as expected

I am encountering an issue with making a CORS request to a server that uses basic authentication. I am using jQuery version 1.5.1 and have the following code snippet: $.ajax({ type: 'GET', global: true, url: theSource, crossDomai ...

How to update an object in an array within a collection using ExpressJS and MongoDB

I'm having trouble updating an array within a collection. I can't seem to find the object in the array and add new values to it. I've tried a few methods, but it looks like I can't use collection methods on arrays? router.post('/m ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Looking for a unique way to access the array at index zero

$i=0; foreach($tagss as $tagdetails) { if($i==0){ $tags_array[]["00"]=array("id"=>$i,"name"=>"all","type"=>"gift_finder","parent_id"=>null,"url"=>"all","readonly"=>"0","deleted"=>"0"); } $tags_a ...

The Facebook messenger checkbox plugin does not appear to be displaying correctly

I have integrated the Facebook Messenger Checkbox Plugin into my AngularJS application by following the guide provided at this link. Initially, I was able to successfully display the messenger checkbox plugin on a page. However, upon navigating to another ...

Using JavaScript, generate an array of objects that contain unique values by incrementing each value by 1

I have an array of objects called arrlist and a parameter uid If the property value has duplicate values (ignoring null) and the id is not the same as the uid, then autoincrement the value until there are no more duplicate values. How can I achieve the a ...

accessing specific data within a JSON object using its index

I have a JSON object with an array structure that contains information about different individuals. I am attempting to extract specific elements from the array of objects. { "data": [ { "_id": "5b62dc6ebef986403db8aafd", "name": "Smitha Vijaya", "designat ...

Design a feature to remove an item from MongoDB using Mongoose with Node.js and express.js on a web application

In my current project, I have implemented CRUD functionality where users can insert data using forms, all of which is stored in a mongoDB database. While everything appears to be working smoothly, I am facing a challenge in creating a button that can delet ...

What is the best way to conceal a div when there are no visible children using AngularJS?

I need help with hiding a parent div only if all the child items are invisible. I have successfully hidden the parent when there are no children, but I am struggling to figure out how to hide it based on visibility. <div ng-repeat="group in section.gro ...

Is there a way to automatically interpret and analyze a gruntfile in order to make changes to it and then resave it?

I'm working on a intricate Yeoman Generator and I'm in search of a solution to parse an existing gruntfile. If anyone knows a JavaScript method for parsing a gruntfile, your assistance would be greatly appreciated. ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...