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 <p id="demo"></p>
What exactly is <p id="demo"></p>
doing in this code?
document.getElementById("age")
is clear as it gets the id of age which is the input.
function myFunction() {
var age,voteable;
age = document.getElementById("age").value;
voteable = (age < 18)? "Too young" : "Old enough";
document.getElementById("demo").innerHTML = voteable;
}
<p>Click the button to check the age.</p>
Age:<input id="age" value="18" />
<p>Old enough to vote?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
innerHTML); here, document. getElementById("myPara") will return our html element as a javascript object which has pre-defined property innerHTML. innerHTML property contains the content of HTML tag.
The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object.
A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With