Home > OS >  jQuery.text() retrieves all spaces and line returns from HTML element
jQuery.text() retrieves all spaces and line returns from HTML element

Time:02-25

I have some text displayed in a HTML table cell. The text includes some spaces and other line returns that are not visible when I look at the HTML output on my screen (just like in the snippet below).

Using jQuery.text() method, all these spaces and line returns are copied along with the text.

What should I use to grab what is visually displayed by my browser (as shown in the Expected output textarea)?

$(function() {
  let str = $('#address').text();
  $('textarea.paste').val(str);
});
div {
  display: inline-block;
  margin-top: 10px;
}
<table>
  <tbody>
    <tr>
      <td id="address">
        Some word<br>

        Some
        more
        words
      </td>
    </tr>
  </tbody>
</table>

<div>
  <code>jQuery.text()</code> output:<br>
  <textarea  rows="7"></textarea>
</div>
<div>
  Expected output:<br>
  <textarea rows="7">Some word&#13;Some more words</textarea>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

You can read the innerText property:

$(function() {
  let str = $('#address').prop('innerText');
  $('textarea.paste').val(str);
});
div {
  display: inline-block;
  margin-top: 10px;
}
<table>
  <tbody>
    <tr>
      <td id="address">
        Some word<br>

        Some
        more
        words
      </td>
    </tr>
  </tbody>
</table>

<div>
  <code>innerText</code> output:<br>
  <textarea  rows="7"></textarea>
</div>
<div>
  Expected output:<br>
  <textarea rows="7">Some word&#13;Some more words</textarea>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related