Dynamic variable creation in a loop by queryselectorAll

Viewed 31

with this code I managed to create a child to each of the elements of the Node list via QueryselctorAll but I need to retrieve the tille ((document.queryseletor(....).title) works but not dynamically...) of the parent div dynamically as a variable to enter it in the innerHTML of the child. Do you have an idea ?

function onloaddiv() {
  for (const item of document.querySelectorAll('.mat_option')) {
    divp = document.createElement("div");
    var2 = document.querySelector(".mat_option").title;
    divp.innerHTML= "" + var2;
    item.append(divp);
  }
}
2 Answers

From your description I'm not 100% sure what you'd like to achieve, but maybe this?

function onloaddiv() {
  for (const item of document.querySelectorAll('.mat_option')) {
    divp = document.createElement("div");
    var2 = item.title;
    divp.innerHTML= "" + var2;
    item.append(divp);
  }
}

You don't need to query selector once again, you already have item in your loop

function onloaddiv() {
  for (const item of document.querySelectorAll('.mat_option')) {
    divp = document.createElement("div");
    divp.innerHTML = item.title;
    item.append(divp);
  }
}

It doesn't work "dynamically", as you say, because document.querySelector(...) returns only first element it could find.

Related