1

I'm relatively new to javascript and am trying to find out why the text content of an element isn't changing when it should. I just want the text content of the '+' to change when clicking the 'click me' button.

The element should change. Why doesn't it work here? A detailed explanation would be very helpful after reading a related post. Thanks for any help.

function change() {
var btnToChange = document.getElementsByClassName("testBtn");

btnToChange.innerHTML = "it changed!";
}
<button class="testBtn">+</button>
<button class="testBtn2" onclick="change()">Click to Change</button>
user8758206
  • 2,106
  • 4
  • 22
  • 45
  • 1
    `getElementsByClassName` returns an array collection for matching class name from DOM. so in this case use `getElementsByClassName('testBtn')[0]` – Shiv Kumar Baghel Sep 04 '18 at 10:53

4 Answers4

5

You need to do document.getElementsByClassName("testBtn")[0]; because document.getElementsByClassName will return you the array of elements that match the class, although there is a single element in the DOM. Since you have one element use [0].

function change() {
  var btnToChange = document.getElementsByClassName("testBtn")[0];

  btnToChange.innerHTML = "it changed!";
}
<button class="testBtn">+</button>
<button class="testBtn2" onclick="change()">Click to Change</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

document.getElementsByClassName("name") gives you an array, the first element of that array is your element. You need to do document.getElementByClassName[0] to get to the element. Try using document.querySelector instead. Also , you can go to the web console to see whats happening to your code.

Mazhar Ali
  • 328
  • 1
  • 3
  • 13
1

You can use querySelector:

function change() {
    var btnToChange = document.querySelector(".testBtn");
    btnToChange.innerHTML = "it changed!";
}

Or with getElementsByClassName:

function change() {
    var btnToChange = document.getElementsByClassName("testBtn")[0];
    btnToChange.innerHTML = "it changed!";
}

Note that querySelector and querySelectorAll are the methods of document and all elements, but getElementsByClassName is only of document.

Văn Quyết
  • 2,384
  • 14
  • 29
1

document.getElementsByClassName returns an array-like object of all DOM elements. You can use document.querySelector or document.getElementsByClassName()[0] to get the first element.

function change() {
  var btnToChange = document.querySelector(".testBtn");
  btnToChange.textContent= "it changed!";
}
Chandru
  • 99
  • 5