Home > Software engineering >  set data attribute to html elements from an array of strings
set data attribute to html elements from an array of strings

Time:02-16

I have the following html structure

<div >
    <div >
        <div >one</div>
        <div >two</div>
        <div >three</div> 
        <div >four</div>
    </div>
    <div >
        <div >one</div>
        <div >two</div>
        <div >three</div> 
        <div >four</div>
    </div>
    <div >
        <div >one</div>
        <div >two</div>
        <div >three</div> 
        <div >four</div>
    </div>
    <div >
        <div >one</div>
        <div >two</div>
        <div >three</div> 
        <div >four</div>
    </div>
    </div>

I'm trying to loop through each of the "cell' class and set data attribute from an array of strings.

For ex. ["a", "b", "c", "d" ...]

The number of "cell" elements and number of elements in the array will always be the same

Expected output should be

<div >
<div >
    <div  data-label="a">one</div>
    <div  data-label="b">two</div>
    <div  data-label="c">three</div> 
    <div  data-label="d">four</div>
</div>
<div >
    <div  data-label="a">one</div>
    <div  data-label="b">two</div>
    <div  data-label="c">three</div> 
    <div  data-label="d">four</div>
</div>
<div >
    <div  data-label="a">one</div>
    <div  data-label="b">two</div>
    <div  data-label="c">three</div> 
    <div  data-label="d">four</div>
</div>
<div >
    <div  data-label="a">one</div>
    <div  data-label="b">two</div>
    <div  data-label="c">three</div> 
    <div  data-label="d">four</div>
</div>    
</div>

I was able to loop through "rows" and convert it to an array of arrays and then got stuck on how to set data-attributes from another array. Do we need to iterate through each of "cell" elements in the ""row" and convert it into array or can we pass the data attribute through any other approach.

let phrases = ["a", "b", "c", "d"]
const rows = document.querySelectorAll(".row");
let cellArray = []
for (let i = 0; i < rows.length; i  ) {
    const cells = rows[i].querySelectorAll(".cell")
    cellArray.push(cells)
}
for (let j = 0; j < cellArray.length; j  ) {
    var value = parent[j];

    for (let k = 0; k < parent[j].length; k  ) {
        var innerValue = parent[j][k];
    }
}

CodePudding user response:

something like that ?

const phrases = 'abcd';

document.querySelectorAll('div.row').forEach( row => 
  {
  row.querySelectorAll('div.cell').forEach((cell,i) => cell.dataset.label = phrases[i])
  })

CodePudding user response:

Below logic, it might help you.

const rows = document.querySelectorAll(".row");
let phrases = ["a", "b", "c", "d"];
for (let i = 0; i < rows.length; i  ) {
    var cells = rows[i].querySelectorAll(".cell");
    console.log(cells.length);
    for (var j = 0; j < cells.length; j  ) {
        cells[j].setAttribute('data-label', phrases[j]); 
    }
}
  • Related