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>

1
  • 1
    getElementsByClassName returns an array collection for matching class name from DOM. so in this case use getElementsByClassName('testBtn')[0] Commented Sep 4, 2018 at 10:53

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

@user8758206 glad to help.
Could also be done by document.querySelector('.testBtn') or document.querySelectorAll('.testBtn')[0] for the first element.
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.

Comments

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.

Comments

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!";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.