0

I'm currently trying to translate the text of a button using JS.

I tried using this method:

function changeButtonText() {
    buyNowButton = document.querySelectorAll("button.buy_now");
    for (var i = 0; i < buyNowButton.length; i++) {
        buyNowButton[i].setAttribute("id", "buyNowButton");
    }
    buyNowButton.innerText = "New Text";
}

Which didn't work. I used the same code for an 'input' element instead of a 'button' element, except that the input had 'buyNowButton.value = "New Text";' and that worked.

Checking the Chrome debugger tool shows that the ID is given to the button element and checking the value by inputting 'buyNowButton.innnerText' also returns the "New Text". The only issue is that the text of the button on the website doesn't actually change. I've tried .innerHTML, .value, .textContent as well without success.

I then found this solution:

document.getElementById('elementID').innerText = 'value;'

and used it like this:

function changeButtonText() {
    buyNowButton = document.querySelectorAll("button.buy_now");
    for (var i = 0; i < buyNowButton.length; i++) {
        buyNowButton[i].setAttribute("id", "buyNowButton");
    }
    document.getElementById('buyNowButton').innerText = "New Text";
}

and it did the job. I'm just confused to why this one worked when the first didn't?

In both instances, I gave the element the ID "buyNowButton". I verified wit the chrome debugger tool - and in essence, the code should do the same thing, right?

Keyan
  • 87
  • 1
  • 11
  • 1
    Duplicate IDs are **invalid HTML**. Do not set the same ID to multiple elements. – CertainPerformance Aug 31 '20 at 20:57
  • Since `querySelectorAll` returns a collection, `buyNowButton.innerText = "New Text";` assigns to a property of the collection, not to any element, so it doesn't do anything. Better to use precise variable names - name the collection something like `buyNowButtons` instead – CertainPerformance Aug 31 '20 at 20:58
  • And if you were expecting `buyNowButton` to find the element with the `id="buyNowButton"` as part of global named elements, then first it wouldn't override the variable you did define with the same name, and second, in case of multiple elements sharing the same `id`, this should also return an HTMLCollection (though FF doesn't respect the specs here, returning only the first in DOM tree order). – Kaiido Sep 01 '20 at 01:00

0 Answers0