I’m looking for the best practice for taking multiple span tags from multiple spans and sticking them into an array (or json object) for later use. (Not even sure whether array or json is the way to go.)
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>
js:
var cars = document.getElementsByClassName('car');
for(var i=0; i<cars.length; i++) {
<what goes best here?>
}
Currently, I’ve created 3 flat arrays for each ID, data, and year, but that seems messy. I’m having trouble figuring out 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",
}
];
My need for this is simple. I will use the information to do some simple replacement of innerHTML like:
document.getElementById(car[id]).innerHTML = car[make]
So, two parts:
1) What would be better for this type of task – multi-dimensional array or json object?
2) what goes in the section of my loop to stick the data into that array or json?
Thanks – I’m still learning.
You can iterate over all the attributes of each element and add each
data-attribute to the corresponding object:DEMO