CodeRatchet CodeRatchet - 1 month ago 4x
Javascript Question

Append text to existing span tag

I have the following HTML

<div class="card-text" data-test-info-type="price">
<div class="price-section price-section--withoutTax ">
<span data-product-price-without-tax="" class="price price--withoutTax">$20.00</span>

I'm trying to append the following text to the $20.00 Prices include taxes

So the end result would be $20.00 Prices include taxes

However I'm hitting a brick wall trying to achieve this I have tried the following:

var span = document.getElementsByClassName("price price--withoutTax");
var txt = document.createTextNode("Prices include taxes");
span.innerText = txt.textContent;

Yet it remained as $20.00

I then tried

document.getElementsByClassName('price price--withoutTax').innerHTML = "hello";

Again same result stayed as $20.00

Can someone shed some light on how I go about appending additional text to a span tag?


The thing is that document.getElementsByClassName return an HTML collection, or a bunch of elements in 'array' sort of structure. So that means, this:

var span = document.getElementsByClassName("price price--withoutTax");
span.innerText = ...;

Will not work because span isn't one element, it's a list. Even if you have one element with the class name, it will return you a list of just one element. If you want only the first element, or are only using the first element, do:

var span = document.getElementsByClassName("price price--withoutTax")[0];

Notice the [0]. This access the first element of the 'array' like return value of document.getElementByClassName, giving you the first element with the given class name. If you want to get the value of more than one of the elements, you can loop over it and do whatever to each element.