Javascript选择嵌套的类元素 [英] Javascript select nested class element
问题描述
我正在努力更改我网站上滑块的一些元素
I'm working on changing some elements the slider on my website
我的滑块代码如下所示:
my slider code looks like this:
<div class="cl1">
<h1>Some heading</h1>
<div class="sl_descr">Some description</div>
<div class="sl_price">from only €00.00<br></div>
</div>
<div class="cl2">
<h1>Some other heading</h1>
<div class="sl_descr">Some other description</div>
<div class="sl_price">from only €00.00<br></div>
</div>
<div class="cl3">
<h1>yet some heading</h1>
<div class="sl_descr">yet Some description</div>
<div class="sl_price">from only €00.00<br></div>
</div>
我想在货币变化时改变价格。要做到这一点,我想使用javascript与getElementsByClassName,然后使用innerHTML。但是我的javascript无法正常工作。这是
I would like to change price when the currency changes. To do that I would like to use javascript with getElementsByClassName and then innerHTML. However my javascript doesn't work as wanted. Here it is
document.getElementsByClassName('cl1 sl_price').innerHTML="from only £00.00<br>";
如何为每个cl元素分别处理sl_price类的任何建议?干杯
any suggestions to how could I separately address "sl_price" class for every "cl" element? Cheers
推荐答案
您当前的尝试有两个问题;
There's two things wrong with your current attempt;
- 您只能将单个类名传递给
getElementsByClassName
-
getElementsByClassName
返回元素的集合(列表)
(因此没有innerHTML
属性)
- You can only pass a single classname to
getElementsByClassName
getElementsByClassName
returns a collection (list) of elements (will therefore not have ainnerHTML
property)
您可以尝试 document.querySelector(。cl1 .sl_price)
(使用css选择器并返回第一场比赛)
You could try document.querySelector(".cl1 .sl_price")
instead (takes a css selector and returns the first match)
在 https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelector
最终结果将是这样的;
The end result would then be something like this;
document.querySelector('.cl1 .sl_price').innerHTML = "from only £00.00<br>";
注意:我假设你只想匹配一个元素。如果没有,你应该看看@ Bommox的回答和 querySelectorAll
。
Note: I am assuming you only wanted to match a single element. If not, you should look at @Bommox's answer and querySelectorAll
.
这篇关于Javascript选择嵌套的类元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!