I need to display the result of the loop FOR
in a DIV
, jumping line, how can I do?
Example
1
2
3
4
5
My Code:
for(i = 0; i <= keyCliente; i++){
document.getElementById("divExibir").innerHTML = i;
}
I need to display the result of the loop FOR
in a DIV
, jumping line, how can I do?
Example
1
2
3
4
5
My Code:
for(i = 0; i <= keyCliente; i++){
document.getElementById("divExibir").innerHTML = i;
}
You have two options, or you use a <br>
that exactly does "line break" or put that content inside a block element, such as p
. Or any other element not "block" but with display: block
in css.
Note:
+=
to avoid being always erasing and writing overhead inside the loop. With +=
it adds. document.getElementById('divExibir');
out of the loop. This line delays the code. <br>
: var keyCliente = 5;
var divExibir = document.getElementById("divExibir")
for (var i = 1; i <= keyCliente; i++) {
divExibir.innerHTML += i + '<br>';
}
<p>
: var keyCliente = 5;
var divExibir = document.getElementById("divExibir")
for (var i = 1; i <= keyCliente; i++) {
var p = document.createElement('p');
p.innerHTML = i;
divExibir.appendChild(p);
}
or, alternatively:
var keyCliente = 5;
var divExibir = document.getElementById("divExibir")
for (var i = 1; i <= keyCliente; i++) {
divExibir.innerHTML += '<p>' + i + '</p>';
}
You can resolve this as follows:
document.getElementById("divExibir").innerHTML = document.getElementById("divExibir").innerHTML + i + '<br>';
When you use innerHTML you replace every loop with everything inside the div and place the new content. That is when he goes through the first loop he added the number 1, when he went through the second loop, he zeroed the div and added 2 and so on, below follows an example of how to keep the original content and add a new one next. Add some% w / w to break the line.
<script>
for (i = 0; i < 10; i++) {
var div = document.getElementById('divExibir');
div.innerHTML = div.innerHTML + i + '<br />';
}
</script>