关于innerText和innerHTML的区别
问题根源:在使用javascript时我们常常需要获取html中某些特定标签的文本,此处常常会用到两种方法,第一种通过innerText获得文本,第二种则是通过innerHTML
但我们常常会会不加以区别的使用两种方法中的任意一种,下面通过代码的执行效果来告诉你这两种方法的区别吧。
代码验证
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>获取标签内容</title>
</head>
<body>
<div id='div'>
<h1>标题</h1>
我是div标签内的文本
<p id='p'>我是段落标签的文本</p>
</div>
</body>
<script>
var div_str1=document.getElementById('div').innerHTML;
var div_str2=document.getElementById('div').innerText;
var p_str1=document.getElementById('p').innerHTML;
var p_str2=document.getElementById('p').innerText;
console.log("div中innerHTML="+div_str1);
console.log("div中innerText="+div_str2);
console.log("p中innerHTML="+p_str1);
console.log("p中innerText="+p_str2);
</script>
</html>
执行效果
从中不难发现,innerHTML会得到标签中的全部内容,innerText会筛选出标签对,仅提取出文本部分