「JavaScript」指定タグ名の文字列(textContent)を変更する

2021年9月27日

書式
タグ要素名.item(インデックス).textContent =文字列

使用例

<div id="cft">
  <p>A01</p>
  <p>B02</p>
</div>
<input type="button" value="テスト" onclick="change()" />
<script>
  function change() {
   //divセレクタid[cft]の取得
    const selId = document.getElementById("cft");
    //pタグの情報の取得
    const ptag = selId.getElementsByTagName("p");
    
    //pタグのtextContentの値の判定
    if (ptag.item(0).textContent === "A01") {
      for (let i = 0; i < ptag.length; i++) {
       //要素の文字列の変更
        ptag.item(i).textContent = "value"+ i;
      }
    }
  }
</script>

 

JavaScript

Posted by arkgame