简体   繁体   English

如何将变量设置为等于元素的innerHTML

[英]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. 我有一个表,我想设置一个等于表的innerHTML的变量。 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. 我已经看到我可以更改元素的innerHTML但我无法弄清楚如何查看元素的内容。

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

You can try this also: Html code: 你也可以尝试这个:Html代码:

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: Javascript代码:

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 从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. 我认为innerHTML是一个只设置属性而不是读取。 I was having an error about 5 lines above the code that's why I was not being able to see the alert(). 我在代码上方有5行错误,这就是我无法看到alert()的原因。 sorry about that! 对于那个很抱歉!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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