通过 js 修改 html 的文本内容或者样式

时间:2023-03-10 01:56:05
通过 js 修改 html 的文本内容或者样式

通过 js 修改 html 的文本内容

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xiao001</title>
</head>
<body>
<h1>this is a js and html code</h1>
<p id = "demo">点击按钮将此处文本替换</p>
<button type="button" onclick="my_function()">点我</button> <script type="text/javascript">
function my_function() {//替换demo里面的文本内容
document.getElementById("demo").innerHTML = "Hello javascript!";
}
</script> </body>
</html>

同时我们可以发现,只要在对应 id 所在标签所包含的文本都会被替换,包括其下级标签包含的内容

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xiao001</title>
</head>
<body>
<h1>this is a js and html code</h1>
<div id = "demo">
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
<p>this will be replace too</p>
</div>
<button type="button" onclick="my_function()">点我</button> <script type="text/javascript">
function my_function() {//替换demo里面的文本内容
document.getElementById("demo").innerHTML = "Hello javascript!";
}
</script> </body>
</html>

通过 js 修改 html 样式

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xiao001</title>
</head>
<body>
<p id="demo">change the color of this paragraph</p>
<button type="button" onclick="my_function()">do it</button> <script type="text/javascript">
function my_function() {
var cnt = document.getElementById('demo');//找到元素
cnt.style.color = "#ff0000";//改变样式
}
</script>
</body>
</html>

同理,只要在对应 id 所在标签所包含的样式都会做出对应变化,包括其下级标签中的样式

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xiao001</title>
</head>
<body>
<div id="demo">
change the color of this paragraph
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
<button type="button" onclick="my_function()">do it</button> <script type="text/javascript">
function my_function() {
var cnt = document.getElementById('demo');//找到元素
cnt.style.color = "#ff0000";//改变样式
}
</script>
</body>
</html>