2

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

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?

Code Ratchet
  • 5,758
  • 18
  • 77
  • 141
  • 2
    `getElementsByClassName` returns a list. You have to set the index (for instance, [0]). – Gerardo Furtado Sep 09 '16 at 03:47
  • What's the point of creating a text node only to retrieve its text content? Why not just use the `"Prices..."` string directly? Also, once you fix the issue with `getElementsByClassName` returning a list, you are overwriting the existing contents of the span, not adding to the contents. – nnnnnn Sep 09 '16 at 03:53
  • @CodeRatchet, I think for a proper solution besides above adding to your question , also check this http://stackoverflow.com/questions/19030742/difference-between-innertext-and-innerhtml-in-javascript#19030857 and – sakhunzai Sep 09 '16 at 04:10
  • and working demo https://jsfiddle.net/n0jmuvw7/ – sakhunzai Sep 09 '16 at 04:17

1 Answers1

2

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.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143