简体   繁体   中英

How can I set the variable equal to the innerHTML of an element

I have a table and I would like to set a variable equal to the innerHTML of a table. I have seen that I can change the innerHTML of an element but I haven't been able to figure out how to see the contents of the element.

var tableHtml = document.getElementById("mytable").innerHTML;

You can try this also: Html code:

Table:<br/>
<table id="tbl" border="1">
    <tr>
        <td>Cell 1.1</td>
        <td>Cell 1.2</td>
        <td>Cell 1.3</td>
    </tr>
    <tr>
        <td>Cell 2.1</td>
        <td>Cell 2.2</td>
        <td>Cell 2.3</td>
    </tr>
</table>
<br />
Message:<br/>
<textarea id="message"/>

Javascript code:

var tbl = document.getElementById('tbl');
var tblinner = tbl.innerHTML; //save the innerHTML to a variable
var message = document.getElementById('message');
message.value = tblinner; //display the innerHTML value

See it in action from jsfiddle.net

The same way you set it:

var tableHTML = document.getElementById('myTable').innerHTML;
alert(tableHTML);
alert(document.getElementById('id_of_the_element').innerHTML);

I thought that innerHTML was a set only property and not read. I was having an error about 5 lines above the code that's why I was not being able to see the alert(). sorry about that!

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