首頁  >  文章  >  web前端  >  如何在JS中改變DOM元素的文字內容

如何在JS中改變DOM元素的文字內容

autoload
autoload原創
2021-04-07 16:10:102753瀏覽

如何在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(&#39;p&#39;);
        console.log(p);
          //textContent:添加文本
        p.textContent ="hello world";
           
  </script>

2.innerText:

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

3.innerHTML:##

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

推薦:《

2021年js面試題目及答案(大總結)

以上是如何在JS中改變DOM元素的文字內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn