Use of document.getElementById in JavaScript

后端 未结 7 942
后悔当初
后悔当初 2021-02-06 08:31

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

相关标签:
7条回答
  • 2021-02-06 09:14

    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>

    0 讨论(0)
  • 2021-02-06 09:15

    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.

    0 讨论(0)
  • 2021-02-06 09:16

    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"

    0 讨论(0)
  • 2021-02-06 09:17

    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

    0 讨论(0)
  • 2021-02-06 09:19

    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)

    0 讨论(0)
  • 2021-02-06 09:22

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

    0 讨论(0)
提交回复
热议问题