In javascript, if we want to obtain the object content, js provides three methods for us: outerhtml, innerhtml, and innertext. But what is the difference between them and their specific usage, maybe many people do not know.
Sample Code:
The Code is as follows: |
Copy code |
<Div id = "test"> <Span style = "color: red"> test1 </span> test2 </Div> |
In JS, you can use:
The Code is as follows: |
Copy code |
Document. getElementById ('test'). innerHTML: |
That is, all content from the start position of the test object to the end position, including its internal Html Tag.
Returned value in the preceding example: <span style = "color: red"> test1 </span> test2
The Code is as follows: |
Copy code |
Document. getElementById ('test'). innerText: |
(Note: innertext is only applicable to IE browsers, so try not to use innertext)
Content from the starting position to the ending position, but it removes the Html Tag.
Returned value in the preceding example: test1 test2, where the span tag is removed.
The Code is as follows: |
Copy code |
Document. getElementById ('test'). outerHTML: |
In addition to all the content of innerHTML, it also contains the matching OBJECT tag itself.
Returned value in the preceding example: <div id = "test"> <span style = "color: red"> test1 </span> test2 </div>
Firefox does not support Js InnerHtml
The original code is as follows:
The Code is as follows: |
Copy code |
<Span id = "ad_1"> </span> <SPAN id = "ad_11" style = "visibility: hidden;"> <Script language = "JavaScript" src = "/js/ad_1.js"> </script> </SPAN> <SCRIPT> ad_1.innerHTML = ad_11.innerHTML; ad_11.innerHTML = ""; </SCRIPT> |
The above code can be correctly executed and replaced in IE, chrome, and other browsers, but not in Firefox. In fact, the solution is also very simple. Let's write code according to ECMAScript specifications. The above code is corrected as follows:
The Code is as follows: |
Copy code |
<Span id = "ad_1"> </span> <SPAN id = "ad_11" style = "visibility: hidden;"> <Script language = "JavaScript" src = "/js/ad_1.js"> </script> </SPAN> <SCRIPT> document. getElementById ("ad_1 "). innerHTML = document. getElementById ("ad_11 "). innerHTML; document. getElementById ("ad_11 "). innerHTML = ""; </SCRIPT> |
Do not directly use the DIV or SPAN id, but use document. getElementById ("div_id") to replace it. In addition, Firefox does not support the innerTEXT attribute.