[英]Populate elements with class name using Javascript
I have some HTML which looks like this 我有一些看起来像这样的HTML
<p>Latte: <span class="hot-drink"></span></p>
<p>Capuccino: <span class="hot-drink"></span></p>
<p>Coca Cola: <span class="cold-drink"></span></p>
<p>Water: <span class="cold-drink"></span></p>
<p>Iced tea: <span class="cold-drink"></span></p>
I would like to use javascript to populate all of the <span>
elements with the class hot-drink
applied to them with the variable hot-drink-status()
. 我想使用javascript用变量
hot-drink-status()
将应用于类的hot-drink
填充所有<span>
元素。
So far I have managed to do this to only one of the elements. 到目前为止,我仅对其中一个元素进行了此操作。 The code I wrote looks like this:
我编写的代码如下所示:
var hot-drink = "Avaiable";
document.querySelectorAll('.hot-drink')[0].innerHTML = hot-drink;
I believe I need to change the [0]
to something else. 我相信我需要将
[0]
更改为其他内容。 I have tried [i]
but this does not work. 我已经尝试过
[i]
但这不起作用。
I know that querySelectorAll
is working as it allows me to apply the script to any element. 我知道
querySelectorAll
正在运行,因为它允许我将脚本应用于任何元素。 I am just unable to apply the script to all element. 我只是无法将脚本应用于所有元素。
The outcome I am looking for is the HTML to be rendered as below 我正在寻找的结果是要呈现的HTML如下
<p>Latte: <span class="hot-drink">Available</span></p>
<p>Capuccino: <span class="hot-drink">Available</span></p>
<p>Coca Cola: <span class="cold-drink"></span></p>
<p>Water: <span class="cold-drink"></span></p>
<p>Iced tea: <span class="cold-drink"></span></p>
All elements with the class hot-drink
are populated with the text "Available" 类别为
hot-drink
所有元素均填充文本“ Available”
Try (do not use minus char in variable names - camel case instead) 尝试(不要在变量名中使用减号- 驼峰式 )
var hotDrink = 'Available'; document.querySelectorAll('.hot-drink').forEach(el=> el.innerHTML= hotDrink)
<p>Latte: <span class="hot-drink"></span></p> <p>Capuccino: <span class="hot-drink"></span></p> <p>Coca Cola: <span class="cold-drink"></span></p> <p>Water: <span class="cold-drink"></span></p> <p>Iced tea: <span class="cold-drink"></span></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.