JS元素节点的属性之修改元素内容
1.innerHTML 获取标签间内容,会解析
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var oDiv = document.getElementById("div1");
alert(oDiv.innerHTML);
oDiv.innerHTML = "<h1>Hello World</h1>";
}
</script>
</head>
<body>
<div id="div1">div文本<em>em文本</em><strong>strong文本</strong></div>
</body>
</html>
运行结果:
2.innerText 获取标签间纯文本,不会解析标签,设置纯文本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var oDiv = document.getElementById("div1");
alert(oDiv.innerText);
oDiv.innerText = "<h1>Hello World</h1>";
}
</script>
</head>
<body>
<div id="div1">div文本<em>em文本</em><strong>strong文本</strong></div>
</body>
</html>
运行结果:
3.outerHTML 从外标签开始到外标签结束
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var oDiv = document.getElementById("div1");
alert(oDiv.outerHTML);
oDiv.outerHTML = "<h1>Hello World</h1>";
}
</script>
</head>
<body>
<div id="div1">div文本<em>em文本</em><strong>strong文本</strong></div>
</body>
</html>
运行结果: