流浪のwolf

卷帝

导航

innerText 和 inner HTML 的区别

获取内容时:

innerText会自动删除空格和换行;innerHTML会保留空格和换行;

<body>
  <div>获              取内    容</div>
<script>
  const div = document.querySelector('div')
  console.log(div.innerText)  // 获 取 内 容
  console.log(div.innerHTML)  // 获 取 内 容
</script>

设置内容时:

innerText不会识别标签;innerHTML会解析标签;

<body>
  <div></div>
<script>
  const div = document.querySelector('div')
  div.innerText = `<h1>设置内容</h1>`  //  <h1>设置内容</h1>   不能识别标签 h1 
  div.innerHTML = `<h1>设置内容</h1>` // 设置内容 解析标签 
</script>

 

posted on 2022-08-04 22:02  流浪のwolf  阅读(48)  评论(0编辑  收藏  举报