0

I'm very new to Javascript and one of the buttons I created can't seem to find the id it's looking for.

<button type="button" onclick=document.getElementById("text").innerHTML = "replacement text">English</button>
<button type="button" onclick='document.getElementById("text").innerHTML = "replacement text"'>Nederlands</button>

<p class=text id=text> 

the first onclick can't find the id from the

and I don't know why. the class=text is used for CSS. If any of you would be so kind to answer what's wrong. It would be greatly appreciated.

  • 1
    Just a word of caution, make sure the text is safe from harmful code injection. in other words: it's better to use `.innerText = str` instead of `.innerHTML = str` whenever possible – Endless Nov 29 '20 at 16:08

2 Answers2

1

You have missing quotes in your first button's onclick handler:

<button type="button" onclick='document.getElementById("text").innerHTML = "replacement text English"'>English</button>
<button type="button" onclick='document.getElementById("text").innerHTML = "replacement text Nederlands"'>Nederlands</button>

<p class="text" id="text">original text</p>
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
1

Add quotes and better practice to end tag <p>:

<button type="button" onclick='document.getElementById("text").innerHTML = "replacement text"'>English</button>
<button type="button" onclick='document.getElementById("text").innerHTML = "replacement text"'>Nederlands</button>

<p class=text id=text></p> 

Another class attribute in p tag is of no use, as you aren't using any CSS or using Javascript to handle it.

Wasif
  • 14,755
  • 3
  • 14
  • 34