1

since many days, I'm stuck with if I want to add <br> with elem.innerHTML += '<br>' or document.createElement('br'), the whole site crashes. But if I am doing this with a normal letter, it works just fine.

  function setSpace(elem){
    if((elem.clientHeight-49)/16 >= 1){
      for(var i=0; i <= (elem.clientHeight-49)/16; i++){
        elem.innerHTML += '<br>';
      }
    }
  }

How can I solve this problem?

4 Answers4

4

The loop risks to never finish, because you extend the height of the element in every iteration, which is also influencing the stop-condition of the loop. elem.clientHeight increases, and i might never get greater than (elem.clientHeight-49)/16.

A way out is to first get the limit into a variable, and then use that:

 function setSpace(elem){
    let end = (elem.clientHeight-49)/16;
    if (end >= 1){
      for(var i=0; i <= end; i++) {
        elem.innerHTML += '<br>';
      }
    }
  }

... but stil be careful, as the next time you call setSpace it will add even more line breaks. If you keep calling this function, you'll never stop adding line breaks.

Review what your purpose really is with this code.

There are better ways to add spacing to an element, for instance with CSS padding-bottom.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    Thank you, it worked. I am currently working on a chat application and because of position:absolute of the messages, I have to iterate through every message and look, whether it has more than one line and set relative to that the
    's to the wrapper.
    – Leonardo Cizmar Oct 25 '19 at 11:38
1

I believe it's just same as this.

Every time innerHTML is set, the HTML has to be parsed, a DOM constructed, and inserted into the document. This takes time.

That's causing your browser crashes. Actually not crashes, but it's still processing.

The solution is, you need to use appendChild.

function setSpace(elem) {
    var space = document.createElement('div');
    var count = (elem.clientHeight-49)/16;

    if (count >= 1) {
        for (var i=0; i <= count; i++) {
            elem.appendChild(space);
        }
    }
}
nmfzone
  • 2,755
  • 1
  • 19
  • 32
-1
  1. Your code seems to work fine and doesnt crash.
  2. If you are trying to increase the height by adding extra
    that would not be the right approach.
    1. Rather suggest to change the height directly by changing the style properties
Murtuza Husain
  • 178
  • 2
  • 14
-1

You can try: elem.innerHTML += '\n'

thang tran
  • 23
  • 4