Why is my inline JavaScript function not working?

What is the problem? The code does not work, the text does not change.

function translate() { document.getElementById("tex").innerHTML = "BLABLA"; } 
 <h1 align="center"><font size="100">What Is BLA: </font></h1> <p id ="tex"><font size="10">BLA</font></p> <button onclick="translate()">Translate</button> 
+6
source share
2 answers

The problem is in some browsers, such as Chrome, the DOM elements have a translate property (MDN does not indicate Chrome as support for this, but it does have a property). In the context of JavaScript event attributes, those shadow properties are any global names with the same name.

If you check the developer console, you will see a message stating that translate not a function because of this.

Uncaught TypeError: translate is not a function

If you change the name of the function, you will avoid this problem:

 function myTranslate() { document.getElementById("tex").innerHTML = "BLABLA"; } 
 <h1 align="center"><font size="100">What Is BLA: </font></h1> <p id ="tex"><font size="10">BLA</font></p> <button onclick="myTranslate()">Translate</button> 
+13
source

It is also possible to note that you are trying to set the innerHTML of the p element with id tex . But an element has a child element in it. You can set the innerHTML property of this element.

 document.getElementById("tex").childNodes[0].innerHTML = "BLABLA"; 
0
source

Source: https://habr.com/ru/post/1013136/


All Articles