首页 >> 综合精选 >

如何在JS中改变DOM元素的文本内容

2022-12-09 16:52:01 来源: 用户: 

跟大家讲解下有关如何在JS中改变DOM元素的文本内容,相信小伙伴们对这个话题应该也很关注吧,现在就为小伙伴们说说如何在JS中改变DOM元素的文本内容,小编也收集到了有关如何在JS中改变DOM元素的文本内容的相关资料,希望大家看到了会喜欢。

在JavaScript中获取元素只是第一步,如何对元素的属性进行更改才是接下里的重要步骤,本文主要讲述了如何在JS中更改DOM元素的内容。

HTML表单内容:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="box"> <p></p> </div> </body> </html>

1.textContent:

<script> const box=document.querySelector(".box"); console.log(box); const p=document.querySelector('p'); console.log(p); //textContent:添加文本 p.textContent ="hello world"; </script>

2.innerText:

<script> const box=document.querySelector(".box"); console.log(box); const p=document.querySelector('p'); console.log(p); p.innerText ="php.cn"; </script>

3.innerHTML:

<script> const box=document.querySelector(".box"); console.log(box); const p=document.querySelector('p'); console.log(p); //将html字符串渲染出来应该使用innerHTML p.innerHTML='<em style="color:red">php.cn</em>'; </script>

推荐:《2021年js面试题及答案(大汇总)》

以上就是如何在JS中改变DOM元素的文本内容的详细内容,更多请关注php中文网其它相关文章!

来源:php中文网

  免责声明:本文由用户上传,与本网站立场无关。财经信息仅供读者参考,并不构成投资建议。投资者据此操作,风险自担。 如有侵权请联系删除!

 
分享:
最新文章