Element does not update contents
-
28-04-2021 - |
Question
Following is the JavaScript code to reveal the Browser details. Its showing no output. Please let me know where I am doing wrong.
<html>
<head>
<title></title>
<script type="text/javascript">
var txt;
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</head>
<body>
<p id="example"></p>
</body>
</html>
La solution
Keep your code in after you have the example p
and it will run fine.
Something like this will work. But, you should always separate your javascript from HTML.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="example"></p>
<script type="text/javascript">
var txt;
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</body>
</html>
Autres conseils
You are running the Javascript before the example
div element exists. Run it later (= at the end of the document).
You're accessing the element while it does not exist yet. The reason for this is that the element is defined later than your script. You'll get null
for the getElementById
call, which results in a TypeError
for accessing .innerHTML
.
Use window.onload
:
window.onload = function() {
var txt;
// ...
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow