I have an existing table. I have the td cells displayed as blocks intentionally. :) My goal is to add labels inside each of the td's by creating spans with a specific class, then prepend them to the table cell. I'm using an array of objects with the label data, an 'icon' and a 'name'.
I'm having trouble applying the icons individually to the td's. They all get grouped together on each cell.
A few issues I'm trying to solve:
- Add each object (one icon and one label) to each cell
- When creating the elements, add an icon class to the icon span and an label class to the label span.
- Apply them appropriately in the order shown in the object
I've tried a bunch of different things (see code comments) and lots of good posts here on SO but this function seems to get me the closest to my goal. Any help is very much appreciated.
let items = [{
id: "🐌",
name: "snail"
},
{
id: "🐜",
name: "ant"
},
{
id: "🪲",
name: "beetle"
},
{
id: "🐝",
name: "honeybee"
},
{
id: "🕷",
name: "spider"
}
];
function createLabel(obj) {
// let loc = document.getElementsByTagName("#profiles td");
let loc = document.querySelectorAll("#profiles td");
if (typeof obj !== "undefined" && obj !== null) {
// loop through td's
for (let i = 0; i < loc.length; i++) {
// apply object data
obj.forEach((item) => {
Object.values(item).forEach((text) => {
// loc.prepend(span);
// I also tried my for loop here with similar weird results
let span = document.createElement("span");
let textNode = document.createTextNode(text);
// 'id' should get .icon
// 'name' should get .label
span.className = 'icon';
span.append(textNode);
loc[i].prepend(span);
});
});
}
}
}
createLabel(items);
<table id="profiles">
<tr>
<td>Snail Stuff</td>
<td>Ant Stuff</td>
<td>Beetle Stuff</td>
<td>Honeybee Stuff</td>
<td>Spider Stuff</td>
</tr>
</table>

