Preserving Newlines When Using ".text" or ".textContent". Possible? Alternatives? Workarounds? - javascript

If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: http://jsfiddle.net/76S7z/2/
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?

As you've already determined, Web browsers don't normally render newline characters \n as line breaks. If you're resistent to adding the line break element <br />, you can use the white-space CSS property with the value pre-line, which will:
Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.
Be sure to check the property's compatibility tables before using.
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
Here's a JSFiddle example.

Related

How to append newline to text value in javascript array?

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.
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.
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.
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.

Should't JavaScript ignore whitespace? Node quirk in Firefox

I encountered this "bug" in the latest verison of firefox and I don't know what causes this behavior and which is the correct result.
HTML
<div><h1 id="heading">First Title</h1></div><div><h1>Second Title</h1></div>
JavaScript
var allDivNodes = document.getElementsByTagName("div");
console.log(allDivNodes[0].childNodes);
console.log(allDivNodes[1].childNodes);
console.log(allDivNodes[0].childNodes.length);
console.log(allDivNodes[1].childNodes.length);
The result I get is the following:
And here is the quirk. If I add spaces in my HTML code and run the same script I get this result:
NEW HTML. JavaScript stays the same
<div>
<h1 id="heading">First Title</h1>
</div>
<div>
<h1>Second Title</h1>
</div>
New Result:
I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?
You could use children instead of childNodes, because of formatting you introduced some text nodes (Yes they are nodes with type 3 not just some whitespace) and childNodes will return all of them.
console.log(allDivNodes[0].children.length);
Or with childNodes you can loop though and ignore the ones with nodeType === 3.
Also similarly you have childElementCount as well which will give you the childElement count and will ignore text nodes.
I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?
Firefox is behaving correctly.
This isn't a JavaScript issue. The DOM counts "whitespace only" areas as text nodes, and so the JavaScript is correctly returning all child nodes it finds.
It was older IE that behaved differently, where such whitespace only areas would be ignored. This has been corrected since IE9.
Basically, anything that appears in the page is represented as a DOM node.
I personally prefer to compress my HTML. It not only reduces the download time, but it also makes the DOM smaller with less to occupy memory, and fewer undesired nodes to work around.

How to replace word break with line break in a textarea

Browsers inserts automatically a word break when text reaches the end of the box.
I would like to make this "invisible" to real \n.
Here is what I have tired:
http://jsbin.com/uraneq/1/edit
Example:
You can try to use wrap="hard" attribute for TEXTAREA element. Older browsers support physical value which has similar meaning as hard (but is invalid at least in HTML5).
​ will not be auto inserted by the browser itself so you cannot match it in auto broken text.
however.. you can match line length to see when there might be a possible linebreak (in case you use a block font)

Preserving white space in an HTML select option

I have a set of html text boxes that take input and when the user clicks an 'add' button uses javascript to take the text input and format a string that is put in an HTML select box. The first of these boxes is supposed to contain a 2 character number but can also accept a blank. The formatted strings would look like this:
01-ABC-O
02-DEF-I
However I need a way to display the blank numbers that lines up with the other elements
-GHI-O
This type of entry will show up fine when the javascript adds the option, but when the page is reloaded and the select is repopulated with the values (I'm using Java, jsp, and struts 1.1 if that helps) it gets the same values(spaces preserved) but the whitespace is no longer shown in the select control (I've looked at the page source, and it looks identical to when the javascript adds the option). I have tried substituting the spaces for but this just prints the string "&nbsp" instead of the space. I've also tried using "pre" html blocks and the css white-space property and neither have worked.
Let me know if any further clarification is needed.
You need to replace the spaces with and it should work - note the closing semi-colon (which is missing from your example in the question)! When you do it through Javascript, most (all?) browsers will automatically render the spaces, but when the spaces are there when the page is loaded all (sometimes all but one) of them will be ignored.
You should also apply a font-family: CSS attribute to the select that specifies mono-spaced font(s) in order to ensure everything lines up properly.
When creating the select option with javascript, to preserve white-space, use "\xa0" - it is a NO-BREAK SPACE char.
You can use the pre css style on the area that you are outputting the value to.
<style type="text/css">
#element {
white-space: pre;
}
</style>
<div id="element">
stuff goes here
</div>
This will preserve all whitespace in the div element (other element types will also work) and then you don't need to worry about using the non breaking space.
Are you going to add it via scripting, you need to use Escape Codes for Space "% A0" which you then decode with unescape ()
logTypeList[i] = new Option(unescape(" kent Agent".replace(/ /g, "%A0")), "theValue");
logTypeList[i] = new Option(unescape(" kent Agent".replace(/ /g, "%A0")), "theValue");
Since unescape is deprecated, you may want to use decodeURI:
logTypeList[i] = new Option(decodeURI(" kent Agent".replace(/ /g, "%C2%A0")), "theValue");
More info at http://www.javascripter.net/faq/mathsymbols.htm
You can use the Unicode Character 'SPACE' (U+0020) instead of ("\u0020")

Make IE respect your whitespace with dynmically changed content

If I have the following line in html:
<span></span> wtf
and then I run the jQuery statement:
$("span").html("test");
It ends up looking like "testwtf" instead of "test wtf". Is there anything I can do about this without changing the html?
This happens because IE is interpreting the space in <span></span> wtf to be a leading space, and omits it (and interprets the HTML as <span></span>wtf). Because IE is interpreting the HTML differently than other browsers, I don't think there's much you can do without changing the HTML, except doing a workaround like
$CONTAINER.html('<span>test</span> wtf')
or an even more extreme workarounds such as
if (jQuery.browser.msie) $("span").html("test "); else $("span").html("test");
Edit: Preliminary testing shows that $("span").html("test "); by itself is also sufficient.

Categories