Can someone explain what the document.getElementById(\"demo\")
line does in the example below?
I understand getElementById gets the id of demo but the id is
document.getElementById("demo").innerHTML = voteable
finds the element with the id demo and then places the voteable
value into it; either too young or old enough.
So effectively <p id="demo"></p>
becomes for example <p id="demo">Old Enough</p>
You're correct in that the document.getElementById("demo")
call gets you the element by the specified ID. But you have to look at the rest of the statement to figure out what exactly the code is doing with that element:
.innerHTML=voteable;
You can see here that it's setting the innerHTML
of that element to the value of voteable
.
Consider
var x = document.getElementById("age");
Here x
is the element with id="age"
.
Now look at the following line
var age = document.getElementById("age").value;
this means you are getting the value of the element which has id="age"
getElementById
returns a reference to the element using its id
. The element is the input
in the first case and the paragraph in the second case.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
the line
age=document.getElementById("age").value;
says 'the variable I called 'age' has the value of the element with id 'age'. In this case the input field.
The line
voteable=(age<18)?"Too young":"Old enough";
says in a variable I called 'voteable' I store the value following the rule :
"If age is under 18 then show 'Too young' else show 'Old enough'"
The last line tell to put the value of 'voteable' in the element with id 'demo' (in this case the 'p' element)
It is just a selector that helps you select specific tag <p id = 'demo'></p>
elements which help you change the behavior, in any event (either mouse or keyboard).