-3

I have a function which returns an html element like addSpan(times),is there a way to return this element as many times as specified in the parameter items ?

vanilla js is welcomed!

function addSpan(times){
 const span = `<span>This is a span</span>`
 
 return span
}

$("body").append( addSpan(2) ) //is supposed to add 2 spans
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Vaggelis
  • 912
  • 5
  • 17

4 Answers4

1

Please use Array.map() function.

function addSpan(times){
  const spans = [...Array(times)].map(val => "<span>This is a span</span>").join('')
  return spans
}
Kirill Savik
  • 1,228
  • 4
  • 7
0

use yield

function* addSpan(times){
  for(var i=0; i < times; i++){
    const span = document.createElement('span');
    span.innerText = "Some text" ;
    yield span;
  }
}


for (let element of addSpan(2)) {
  $("body").append(element)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
A.T.
  • 24,694
  • 8
  • 47
  • 65
0

Yes. Possible.

Like this:

function addSpan(count)
{
   let result = "";
   for (var i = 0; i < count; i++)
   {
     result += "<span>This is a span</span>";
   }
   return result;
}
Petr Fořt Fru-Fru
  • 858
  • 2
  • 8
  • 23
0

You need loop until you reach the count and return spans.

function addSpan(times){
 let spans = "";
 const span = `<span>This is a span</span>`;

 for (let i = 0; i < times; i++){
    spans += span;
 }
 
 return spans;
}

$("body").append(addSpan(2));
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Ran Turner
  • 14,906
  • 5
  • 47
  • 53