1.功能说明:
innerHTML 设置或获取位于对象起始和结束标签内的 HTML
outerHTML 设置或获取对象及其内容的HTML形式
innerText 设置或获取位于对象起始和结束标签内的文本
outerText 设置(包括标签)或获取(不包括标签)对象的文本
2.设置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>设置</title> </head> <body> <ol> <li><span id="innerHTML"></span></li> <li><span id="outerHTML"></span></li> <li><span id="innerText"></span></li> <li><span id="outerText"></span></li> </ol> </body> <script type="text/javascript" charset="utf-8"> document.getElementById("innerHTML").innerHTML = "innerHTML"; document.getElementById("outerHTML").outerHTML = "outerHTML"; document.getElementById("innerText").innerText = "innerText"; document.getElementById("outerText").outerText = "outerText"; </script> </html>
在浏览器下f12可以看到dom的渲染情况
<ol> <li><span id="innerHTML">innerHTML</span></li> <li>outerHTML</li> <li><span id="innerText">innerText</span></li> <li>outerText</li> </ol>
3.获取
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>获取</title> </head> <body> <div id="div"> <span id="span1" style="color:red">span1</span> span2 </div> </body> <script type="text/javascript" charset="utf-8"> var innerHTML = document.getElementById("div").innerHTML; var outerHTML = document.getElementById("div").outerHTML; var innerText = document.getElementById("div").innerText; //Firefox不支持 var outerText = document.getElementById("div").outerText; //Firefox不支持 //输出<span id="span1" style="color:red">span1</span> span2 console.info(innerHTML); //输出<div id="div"><span id="span1" style="color:red">span1</span> span2</div> console.info(outerHTML); //输出span1 span2 console.info(innerText); //输出span1 span2 console.info(outerText); </script> </html>
在浏览器下f12可以看到控制台打印情况
<span id="span1" style="color:red">span1</span> span2 <div id="div"> <span id="span1" style="color:red">span1</span> span2 </div> span1 span2 span1 span2
4.用正则表达式去除HTML标签,下面是一个简单的符合W3C标准的示例:
console.info(document.getElementById('div').innerHTML.replace(/<.+?>/gim,''));