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>
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>";
any suggestions to how could I separately address "sl_price" class for every "cl" element? Cheers
getElementsByClassName
returns a collection (list) of elements
(will therefore not have a innerHTML
property)
You could try document.querySelector(".cl1 .sl_price")
instead (takes a css selector and returns the first match)
read more at 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>";
Note: I am assuming you only wanted to match a single element. If not, you should look at @Bommox's answer and querySelectorAll
.
document.querySelectorAll('.cl1 .sl_price');
This will select all nested sl_price elements inside cl1. If you are looking to modify more cl's (i.e. cl1, cl2, cl3) just add a common class to all of them such as cl.
You should do like this (if not using jQuery):
I have used "for" because I don't you if it may be more than one cl1 or sl_price whithin them.
var nodes = document.getElementsByClassName("cl1");
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i].getElementsByClassName("sl_price");
for(var j = 0; j < node.length; i++) {
node.innerHTML="from only £00.00<br>";
}
}
If you use Jquery, the code is shorter than in native Javascript.
$('.cl1 .sl_price').html("from only £00.00<br>");
Here is the fiddle:
http://jsfiddle.net/4zLbmrLq/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With