15.5.1 Element Content As HTML
Reading the innerHTML property of an Element returns the content of that element as a string of markup. Setting this property on an element invokes the web browser’s parser and replaces the element’s current content with a parsed representation of the new string. (Despite its name, innerHTML can be used with XML elements as well as HTML elements.)
Web browsers are very good at parsing HTML and setting innerHTML is usually fairly efficient, even though the value you specify must be parsed. Note, however, that repeatedly appending bits of text to the innerHTMLproperty with the +=operator is usually not efficient because it requires both a serialization step and a parsing step.
innerHTML was introduced in IE4. Although it has long been supported by all browsers, it has only become standardized with the advent of HTML5. HTML5 says that innerHTML should work on Document nodes as well as Element nodes, but this is not universally supported yet.
HTML5 also standardizes a property named outerHTML. When you query outerHTML, the string of HTML or XML markup that is returned includes the opening and closing tags of the element on which you queried it. When you set outerHTML on an element, the new content replaces the element itself. outerHTMLis defined only for Element nodes, not Documents. At the time of this writing, outerHTML is supported by all current browsers except Firefox. (See Example 15-5 , later in this chapter, for an outerHTML implementation based on innerHTML.)
Another feature introduced by IE and standardized by HTML5 is the insertAdjacentHTML() method, which allows you to insert a string of arbitrary HTML markup “adjacent” to the specified element. The markup is passed as the second argument to this method, and the precise meaning of “adjacent” depends on the value of the first argument. This first argument should be a string with one of the values “beforebegin”, “afterbegin”, “beforeend” or “afterend”. These values correspond to insertion points that are illustrated in Figure 15-3 .
Figure 15-3. Insertion points for insertAdjacentHTML()
insertAdjacentHTML() is not supported by current versions of Firefox. Later in this chapter, Example 15-6 shows how to implement insertAdjacentHTML() using the
15.5 Element Content | 379
innerHTML property and also demonstrates how to write HTML insertion methods that do not require the insertion position to be specified with a string argument.欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27935.html