Use of document.getElementById in JavaScript

2019-03-21 15:22发布

问题:

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>

回答1:

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.



回答2:

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)



回答3:

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"



回答4:

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>



回答5:

Here in your code demo is id where you want to display your result after click event has occur and just nothing.

You can take anything

<p id="demo">

or

<div id="demo"> 

It is just node in a document where you just want to display your result.



回答6:

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



回答7:

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).