简体   繁体   中英

How to convert an HTML table to plain text and save it into a variable in JavaScript

I was checking the site and found JavaScript: How to strip HTML tags from string? but this doesn't really explains how to take this:

<tr id="element.incident.comments.additional">
<td colspan="2">
<span style="">
<table cellpadding="0" cellspacing="0" style="table-layout:fixed" width="100%">
<tbody>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr style="">
<td class="tdwrap"><strong>2014-01-23 14:45:40 - <a style="color:blue" href="sys_user.do?sysparm_view=itil&amp;sysparm_query=user_name=Superhero@superhero.com">SuperHero</a></strong></td>
<td align="right" nowrap="true"><sup>Additional comments</sup></td></tr>
<tr style="">
<td colspan="2"><span style="word-wrap:break-word;">received from: SDUperhero@superhero.com<br><br>lalalalalala
<br>lotsofwords<br><br><br><br><br><br>
The information transmitted, including any attachments, is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material</span></td></tr></tbody></table></span></td>
</tr>

and get the text inside:

<tr id="element.incident.comments.additional"> 

for further parsing.

I tried with

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

var commentsField = document.getElementById("element.incident.comments.additional").innerHTML;


alert(strip(commentsField));

but I'm not sure if this is the right way as I'm not getting anything in the alert.

Any thoughts?

Because you have . in your ids, you will need to escape them in your jQuery selector:

$("#txt").val($("#element\\.incident\\.comments\\.additional").html());

and that should work.

jsFiddle : http://jsfiddle.net/hescano/EQ9b3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM