Home > Software design >  How to append newline to text value in javascript array?
How to append newline to text value in javascript array?

Time:09-23

I have a narrow button that contains an image and label text. The state of the button changes to one of several values which are stored as text in an array and then changed out with textContent.

enter image description here

One of the values forces a line break in the label text. I would like to reserve the "blank line" below my label so that layout isn't affected every time the label breaks to two lines of text. To accomplish this, I'm trying to append a newline to every single-line value. For layout reasons, I can't simply pad the container — I need it to match the height of a line of formatted text.

Is there any way to put a newline into a text array value? I've tried adding a CR to my text both within the array and prior to the array as a variable using:

Labelname   \n
Labelname\n 
Labelname<br /> (HTML, I know)
var label = 'Labelname'   String.fromCharCode(13)

Nothing seems to make the newline "stick," and the console reveals the value "Labelname" without the newline.

CodePudding user response:

HTML generally ignores whitespace (including newline characters). To have it rendered, you need to use an element that doesn't ignore whitespace (like <pre>), or opt in to <pre>-style whitespace handling via CSS with white-space: pre-wrap.

CodePudding user response:

I ended up using innerHTML to put formatted text into the element. I was resistant to using it for various reasons, but it provided a straightforward solution to this problem.

  • Related