1

I wanted to make a javascript loop in html like the following:

( if (var i=0; i<10; i++) { )  //<-- JAVASCRIPT

//HTML

( } ) //<-- JAVASCRIPT

I tried using the <% JAVASCRIPT %> but it won't work for me. Does anyone know who to solve this?

Thanks in advance.  

2
  • 6
    I'm pretty sure you can't do this with javascript. Commented Jul 20, 2017 at 20:01
  • Take a look at some template engine, and check out what if does ... Commented Jul 20, 2017 at 20:11

3 Answers 3

7

This is not how javascript works. This is something you would do with PHP.

With javascript, you run it seperately from the html. Then, you create an element within your html as a wrapper to put the javascript generated html into. Like so:

HTML

<div id="myHTMLWrapper">

</div>

<script>
  var wrapper = document.getElementById("myHTMLWrapper");

  var myHTML = '<span class="test">Testing out my script!</span>';

  wrapper.innerHTML = myHTML
</script>

See a working example here

Sorry I skipped over the for loop by the way. Let me fix it with this update... You could do it like this, you see:

<script>
  var wrapper = document.getElementById("myHTMLWrapper");

  var myHTML = '';

  for (var i = 0; i < 10; i++) {
    myHTML += '<span class="test">Testing out my script! loop #' + (i + 1) + '</span><br/><br/>';
  }

  wrapper.innerHTML = myHTML

</script>
Sign up to request clarification or add additional context in comments.

Comments

1

for loops are control flow and thus cannot be inserted into a static context. Try mapping it, e.g.

`<html>` + data.map(function(a) { return `<div>${a}</div>` }).join('') + `</html>`

Comments

-1
<script>
    for(var i=0; i<10; i++) {
    //Code here
    }
</script>

https://www.w3schools.com/js/js_if_else.asp

https://www.w3schools.com/js/js_loop_for.asp

I'd suggest you read a bit before going straight into coding Either way your script seems deficient and I cant make out what you are trying to do with it.

Check these links if you want to append elements: https://www.w3schools.com/jquery/html_append.asp

https://www.w3schools.com/jsref/met_node_appendchild.asp

3 Comments

This doesn't seem to be what OP asked and won't help him. He apparently thinks you can break the script to render HTML as you would with razor script or PHP....
Oh, sorry, im updating my answer then.
Late reply, but I think this answer works. OP confused for with if. The //Code here section could be replaced with a document.write().

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.