Show Data in Div Jumping Line

Asked

Viewed 1,244 times

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;
}

3 answers

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>

Source

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:

  • you have to use += to avoid constantly erasing and writing over the loop. With the += he adds.
  • changes the document.getElementById('divExibir'); out of the loop. This line delays the code.

Using <br>:

var keyCliente = 5;
var divExibir = document.getElementById("divExibir")
for (var i = 1; i <= keyCliente; i++) {
    divExibir.innerHTML += i + '<br>';
}

jsFiddle: https://jsfiddle.net/euerct5u/3/

Using <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);
}

jsFiddle: https://jsfiddle.net/euerct5u/4/

or, alternatively:

var keyCliente = 5;
var divExibir = document.getElementById("divExibir")
for (var i = 1; i <= keyCliente; i++) {
    divExibir.innerHTML += '<p>' + i + '</p>';
}

jsFiddle: https://jsfiddle.net/euerct5u/5/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.