Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of document.getElementById in JavaScript

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>
like image 593
user2931781 Avatar asked Oct 29 '13 11:10

user2931781


People also ask

What is the use of document getElementById () innerHTML?

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.

What is the use of document object in JavaScript?

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.

What can I use instead of document getElementById?

A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.

What is the use of document object?

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.


2 Answers

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.

like image 82
BoltClock Avatar answered Oct 18 '22 05:10

BoltClock


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"

like image 32
Ranadheer Reddy Avatar answered Oct 18 '22 03:10

Ranadheer Reddy