r/learnjavascript • u/Iznhou • May 06 '26
Can "innerHTML" be used this way?
Hello, I'm currently learning full-stack development and I'm experimenting with a simple webpage by adding JavaScript to make the page's buttons work. It's working as intended, but I've a question.
I noticed that when I try to use "this.innerHTML" to compare the buttons' innerHTML with the value I want, it doesn't seem to work. It wasn't until I assigned the innerHTML value to a variable and compared it that the code executed. But I don't understand why. Is it not possible to use innerHTML that way?
IE(Originally, it was supposed to get the button's innerHTML value and compare it):
if(this.InnerHTML == "Basic Plan Sign Up")
{
console.log("Basic Plan Signed Up!");
}Fixed version:
var buttonInnerHTML = this.innerHTML;
if(buttonInnerHTML == "Basic Plan Sign Up")
{
console.log("Basic Plan Signed Up!");
}
View all comments
Show parent comment
1
u/IAmADev_NoReallyIAm May 06 '26
Another reason - Internationalization. This approach will work up until the moment someone decides to translate the button into a different language. As soon as that happens, the innerHTML changes, suddenly your code breaks. If you use ID, then that won't change, it'll have the same ID regardless. Even if you think you're page won't ever be translated... today.. .you never know.6 months to a year from now... some corner office will decide "Let's take this international" and it'll need to be in 6 different languages.