NoPhpGeek NoPhpGeek - 8 days ago 5
HTML Question

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>


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

xec xec
Answer

There's two things wrong with your current attempt;

  1. You can only pass a single classname to getElementsByClassName
  2. 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.

Comments