Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the HTML contained within a td using jQuery?

I have a table cell that contains HTML, e.g.,

    <td id="test">something&trade; is here</td>

I have an input field that I want to use to edit the HTML inside the table cell, e.g.,

    <input type="text" id="editor" value="">

I need to get the string something&trade; is here from the table cell so I can put it into the <input> for editing. I have tried

    var txt=$("#test").text();
    var htm=$("#test").html();

Both of them are returning "something™ is here" rather than the raw HTML - I have a breakpoint in Firebug immediately after setting the two test values, and that's what I'm seeing.

Reading the jQuery documentation, I really expected the .html() method to return the raw HTML I'm looking for, but that's not what is happening.

I know that Javascript doesn't have an encoder like PHP's htmlspecialchars() function and that I have to work around that, but all four of these operations produce the same results:

    var enchtm=$("<div/>").text(htm).html();
    var enctxt=$("<div/>").text(txt).html();
    var htmenc=$("<div/>").html(htm).text();
    var txtenc=$("<div/>").html(txt).text();

Every permutatation puts "something™ is here" in the editfield, not the raw HTML.

How do I get the string something&trade; is here from the table cell into the <input> so I can edit it?

like image 297
FKEinternet Avatar asked Nov 06 '17 07:11

FKEinternet


1 Answers

It doesn't exist. Entities are decoded before the DOM is produced, and .html() (which is really just a wrapper for the innerHTML property) doesn't re-encode it because there's no reason for it to -- something™ is exactly as valid a representation of the HTML as something&trade; is. There is no "completely raw" (pre-character-decoding) view of the HTML provided by the browser.

Suggestion: provide the initial value as the value attribute of the input, instead of having it as the content of the div, so that the flow of data is always one way and this problem doesn't occur.

like image 113
hobbs Avatar answered Oct 16 '22 23:10

hobbs