0

I'm currently trying to implement a function that randomly generates a random number of span tags using a loop. If I wrap the span tags in a string then the spans render onto my page as a string, however, if I don't wrap it in a string, it renders as an object.

Does anyone know of a way to handle this?

function generateRandomStarCount (){
  Math.round(Math.random()*5)
  let result = '';
  for (var i = 0; i < Math.round(Math.random()*5); i++){
    result += '<span className="fa fa-star checked"></span>'
  } 
  return result;
}

1

4 Answers 4

1

Use document.createElement() to create the span elements then append them to the DOM.

function generateRandomStarCount () {
  let result = [];
  
  for (var i = 0; i < Math.round(Math.random()*5); i++){
    let span = document.createElement('span')
    span.className = 'fa fa-star checked'
    result.push(span)
  } 

  return result;
}

let stars = generateRandomStarCount()
stars.forEach(star => document.body.appendChild(star))
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Fragments for storing all the span elements;

function generateRandomStarCount (){
  const fragment = new DocumentFragment();
  for (var i = 0; i < Math.round(Math.random()*5); i++){
      const span = document.createElement('span');
      span.classList.add('fa fa-star checked');
      fragment.appendChild(span)
  } 
  return fragment;
}

Once you get the fragments, just append wherever you want in the document.

 element.appendChild(fragment);

Comments

0

You can use something like:

function generateRandomStarCount() {
   element = document.getElementById('yourElement');
   for (let i = 0; i < Math.round(Math.random()*5); i++){
     var newSpan = document.createElement("span");
     newSpan.className = "fa fa-star checked";
     element.appendChild(newSpan);
   }
}

This code will create a random number of span inside the "yourElement" element.

Comments

0
function generateRandomStarCount () {
  const randomNumber = Math.round(Math.random() * 5)
  const container = document.createElement('div')

  for (var i = 0; i < randomNumber; i++) {
    const spanEl = document.createElement('span')
    spanEl.className = 'span-item'
    spanEl.innerHTML = `Count: ${i}`
    container.append(spanEl)
  }
  return container
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.