2
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;
}
2
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;
}
1
You can solve it this way:
document.getElementById("divExibir").innerHTML = document.getElementById("divExibir").innerHTML + i + '<br>';
1
When you use innerHTML you replace every loop everything that is inside the div and place the new content. In other words, when passing through the first loop he added the number 1, when passing through the second loop he Zera the div and added the 2 and so on, below follows an example of how to save the original content and add a new one then. I joined with a <br />
to break the line.
<script>
for (i = 0; i < 10; i++) {
var div = document.getElementById('divExibir');
div.innerHTML = div.innerHTML + i + '<br />';
}
</script>
1
You have two objections, or you use one <br>
that makes exactly "line break" or puts that content inside a block element, such as the p
. Or any other element not "block" but with display: block
in css.
Note:
+=
to avoid constantly erasing and writing over the loop. With the +=
he 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>';
}
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.