简体   繁体   中英

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

I have a table cell that contains HTML, eg,

    <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, eg,

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

I need to get the string something&trade; is here 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 something&trade; is here from the table cell into the <input> so I can edit it?

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.

As the other answers have indicated, what I was trying to do is literally impossible - the original HTML source code that was used to populate the table cell no longer exists in the browser by the time it gets written to the DOM document.

The way I worked around this was using a title attribute on the table cell, eg,

    // in the PHP/HTML source document
    <?php $text='something&trade; is here'; // the contents of the table cell ?>
    <td id="test" title="<?php echo htmlspecialchars($text) ?>"><?php echo $text ?></td>

Now the Javascript is relatively simple:

    $("#editor").val($("#test").attr("title"));

The problem with this is that some of these table cells are supposed to have tooltips - which use the title attribute - and some are not. Fortunately for me, the table cells that may contain HTML that needs to be edited never need to show a tooltip, and the ones that show tooltips have simple text that can be retrieved using the .text() method. I can set a class attribute on the cells that need a tooltip, eg,

    <td class="tooltipped" title="This is a tooltip">Hover here!</td>

I can then use jQuery's .not() method to suppress the tooltips on the cells were the title is being used for storing encoded HTML:

    // suppress browser's default tooltip on td titles
    $("td[title]").not(".tooltipped").mouseover(function()
    {   var elem=$(this);
        elem.data("title",elem.attr("title"));
        // Using null here wouldn't work in IE, but empty string does
        elem.attr("title","");
    }).mouseout(function()
    {   var elem=$(this);
        elem.attr("title",elem.data("title"));
    });

Javascript has escape function but it won't help you in this case, I just did a trick for you, but stay to get best answer.

 var htm = $("#test").html().replace(/™/g, '&trade;'); $('#editor').val(htm); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td id="test">something&trade; is here</td> </tr> </table> <input type="text" id="editor" value=""> 

I don't think that you would be able to get the exact value as html parses the document and displays the it on the browser and I don't know of any keyword or library that helps to find the exact contents of the element. But you would use Ajax in this case and get all the contents of the file in the string format to get the exact value.

 var client = new XMLHttpRequest(); client.open('GET', './file.html'); // get the file by location client.onreadystatechange = function() { if (client.readyState === 4) { if (client.status === 200) { // when the file is ready var file_contents = (client.responseText); // the whole file is stored in the string format in the variable get_value(file_contents); // function get_value fetches the exact value } } } client.send(); function(str_file) { var indextest = str_file.indexOf("test"); // fetches the index of test var indexclosing = str_file.indexOf("</td>"); // fetches the index of closing td tag var td_content = ""; var condition = false; for (var i = indextest; i < indexclosing; i++) { if (str_file.charAt(i - 1) == ">") { condition = true; // the condition is true when the previous character is '>' } if (condition) { // when the condition is true start storing the value in the td_content element td_content += str_file.charAt(i); } }; console.log(td_content) // display it }; 

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