element.innerHTML

« DOM 参考

摘要

innerHTML sets or gets all of the markup and content within a given element.

语法

var markup = element.innerHTML;
element.innerHTML = markup;
  • 在上例中markup是包含元素(以及子元素)内容的字符串。元素的内容以原始HTML代码显示出来。 例如 "<p>Some text</p>".

示例

// HTML:
// <div id="d"><p>Content</p>
// <p>Further Elaborated</p>
// </div>

d = document.getElementById("d");
dump(d.innerHTML);

// the string "<p>Content</p><p>Further Elaborated</p>" 
// is dumped to the console window

注意

Though not actually a part of the W3C DOM specification, this property provides a simple way to completely replace the contents of an element. For example, the entire contents of the document body can be deleted by:

document.body.innerHTML = "";  // Replaces body content with an empty string.

The innerHTML property of many types of elements—including BODY or HTML—can be returned or replaced. It can be used to view the source of a page that has been modified dynamically:

// Copy and paste into address bar as a single line
javascript:x=document.body.innerHTML.replace(/</g,'&lt;').replace(/\n/g,'<br>'); document.body.innerHTML = x;

As there is no public specification for this property, implementations differ widely. For example, when text is entered into a text input, IE will change the value attribute of the input's innerHTML property but Gecko browsers do not.

It should never be used to write parts of a table—W3C DOM methods should be used for that—though it can be used to write an entire table or the contents of a cell.

规范

DOM Level 0 不属于任何标准.

参考

MSDN innerHTML

其它

  • innerDOM - For those wishing to adhere to standards, here is one set of JavaScript functions offering to serialize or parse XML so as to set element contents defined as string(s) via the DOM or getting element contents obtained from the DOM as a string.

Document Tags and Contributors

Contributors to this page: zezhou, 巴别塔工人
最后编辑者: zezhou,