如何更改多个元素?

我将 var 更改为 class,但这里可能有一些错误。


在这里,我想要这个段落,用户可以在其中更改下一段的名称。我使用的代码只更改了一个名称,但其余的保持不变。


  <script type="text/javascript">

    function changey(){

      var userInput = document.getElementById('userInput').value;

      var list = document.getElementByClassName('kiddo');


      for (let item of list) {

         item.innerHTML = userInput;

      }

    }

</script>


<input id="userInput" type="text" value="Name of kid" />

<input onclick="changey()" type="button" value="Change Name" /><br>


Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!

没有错误消息,代码只更改一个名称而不是所有三个。


慕的地6264312
浏览 166回答 3
3回答

慕桂英4014372

在 html 中使用class="kiddo"而不是id。然后var kiddos = document.getElementsByClassName('kiddo'),您可以使用which 将返回存储在kiddos.然后你只需要遍历这些值并改变你想要的。下面的循环示例:for (var i = 0; i < kiddos.length; i++) {&nbsp; &nbsp; &nbsp;kiddos[i].innerHTML = userInput;}

UYOU

您好,您不应该使用 id,而是使用 class。Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!在 Js 部分之后:<script type="text/javascript">&nbsp; &nbsp; function changey(){&nbsp; &nbsp; &nbsp; var userInput = document.getElementById('userInput').value;&nbsp; &nbsp; &nbsp; var list = document.getElementByClassName('kiddo');&nbsp; &nbsp; &nbsp; for (let item of list) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;item.innerHTML = userInput;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript