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. Jul 20, 2017 at 20:01
  • Take a look at some template engine, and check out what if does ...
    – Teemu
    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>
0
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>`
-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
  • 1
    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....
    – NoobishPro
    Jul 20, 2017 at 20:08
  • Oh, sorry, im updating my answer then.
    – Klajdi
    Jul 20, 2017 at 20:11
  • Late reply, but I think this answer works. OP confused for with if. The //Code here section could be replaced with a document.write().
    – Tony
    Jun 18 at 6:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.