Home > Back-end >  How to use this JavaScript for multiple IDs in HTML?
How to use this JavaScript for multiple IDs in HTML?

Time:06-29

I found this script in the web: https://sebhastian.com/javascript-multiply-string/

let multi = 2;
let str = "Little lamb";
let multiStr = "";

while(multi > 0){
  multiStr  = str
  multiStr  = " ";
  multi--;
}

multiStr = multiStr.trimEnd();
console.log(multiStr); // "Little lamb Little lamb"

document.getElementById("frameText").innerHTML = multiStr;

and would like to ask how to use it on multiple HTML Tags with the ID "frameText". They should all have then the same textstrings. I guess its made with a for loop or so. I am absolute beginner in JavaScript.

CodePudding user response:

You cannot reuse an id as it is invalid HTML, and JavaScript will only ever recognize the first element with a particular id. For selecting multiple elements you should assign them all a common class name, then use document.querySelectorAll(".the_class") to find them and .forEach() to iterate through the result set.

let multi = 2;
let str = "Little lamb";
let multiStr = "";

while (multi > 0) {
  multiStr  = str
  multiStr  = " ";
  multi--;
}

multiStr = multiStr.trimEnd();
console.log(multiStr); // "Little lamb Little lamb"
document.querySelectorAll(".frameText").forEach(ft => ft.innerHTML = multiStr);
<div ></div>
<div ></div>
<div style="padding: 2em;">
  <span ></span>
</div>

CodePudding user response:

let multi = 2;
let str = "Little lamb";
let arr = [];

for (var i = 0; i < multi; i  ) {
  arr.push('<div >'   str   '</div>')
}
document.getElementById("container").innerHTML = arr.join("\n");
<div id="container"></div>

  • Related