Skip to content

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 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 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>

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)


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.

User contributions licensed under: CC BY-SA
8 People found this is helpful