View Data in Div Jumping Row

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;
}
    
asked by anonymous 22.10.2016 / 01:27

3 answers

1

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:

  • You must use += to avoid being always erasing and writing overhead inside the loop. With += it 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: link

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: link

or, alternatively:

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

jsFiddle: link

    
22.10.2016 / 08:36
1

You can resolve this as follows:

document.getElementById("divExibir").innerHTML = document.getElementById("divExibir").innerHTML + i + '<br>';
    
22.10.2016 / 01:45
1

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>

Font

    
22.10.2016 / 01:45