jQuery .contents() Newlines

Test

Test

Test
When I grab a block of text like that with .contents() it returns:

TestTestTest
How can I get it to preserve newlines, is it possible with a RegEx?

I don’t know what you’re doing (obviously, as there’s no code from you yet) but a simple test seem to work fine.


<html>
<head>
</head>
<body>
<button id="get">Get contents and paste</button>
<div id="test">
<p>test</p>
<p>test</p>
<p>test</p>
</div>
<p>Pasted content section is below
<div id="paste"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$('#get').on('click', function () {
    var contents = $('#test').contents();
    $('#paste').html(contents);
});
</script>
</body>
</html>

Here’s a mockup: http://z2.ifrm.com/10717/129/0/p1036209/mockup.html

View applicable codes in the page source. As you can see, the newlines are lost in the textarea upon clicking the Quote button.

Thanks, so now we know what we’re dealing with.

You want to use jQuery to translate this HTML:


<td colspan="4" class="c_post">
	Test<br /><br />Test<br /><br />Test
</td>

in to something like the following text for the textarea content:


Test

Test

Test

Now that we know what we’re dealing with, it should be easier for others to help you with that too.

Yes, that’s pretty much what I’m trying to do, but I just don’t get how to do it. I tried .html(), but it didn’t work.

I’m not sure if jQuery has a way to do this, but it can be done without using jQuery’s library with the following:


<html>
<head>
</head>
<body>
<div colspan="4" class="c_post">
	Test<br /><br />Test<br /><br />Test
</div>
<textarea id="quickcompose" rows="6"></textarea>
<script src="script.js"></script>
</body>
</html>


var content = document.querySelector('.c_post').innerHTML;
content = content.replace(/^\\s*/, '');
content = content.replace(/<br>/g, '\
');
document.getElementById('quickcompose').value = content;