Click here to Skip to main content
15,919,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
On sololearn, when I was learning the getElementById() method, they put the example in JS below, which assumes that the HTML contains an element like
HTML
<p id = "demo"></p>


This is what they put on the JS page.

JavaScript
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";


What I have tried:

So on the html page in the body tag, I put
HTML
<p id="demo">Hey</p>
and I put the code given on the JS page, but it returned "Hey" instead of "Hello World!"
So what did I do wrong?
Posted
Updated 22-Nov-17 6:07am
v2
Comments
W Balboos, GHB 22-Nov-17 11:46am    
What we don't know:
How does your HTML page see the javascript?
Does the javaScript execute before the control is rendered?
F-ES Sitecore 22-Nov-17 11:56am    
The order things appear on the page is important. I'm going to guess your javascript appears before the "p" tag, so it runs before the tag exists. Move your javascript to below the "p" tag.

1 solution

When you write HTML it is presented to the user exactly as you write it, unless some other code causes it to change. So when you write this:
HTML
<p id="demo">Hey</p>
It generates a paragraph tag which displays the word "Hey".

WHen you write Javascript, it does nothing unless something specifically happens to execute that code. So when you write this:
JavaScript
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
it will change the inner text, but only if the code is in a function that gets executed.

Since the text doesn't change, the Javascript is not being executed. See here: Tryit Editor v3.5[^] and it will change when you click the button, because teh JS code is inside a click handler function.
 
Share this answer
 
Comments
Member 13502831 22-Nov-17 12:26pm    
But what other functions can the code be in other than a click handler function? Thanks.
OriginalGriff 22-Nov-17 12:50pm    
You want a list? There are loads of things that Javascript can react to!
See here:
http://www.way2tutorial.com/javascript/javascript_events_handlers.php
CPallini 22-Nov-17 13:04pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900