Skip to content

Document.getElementById()

 document.getElementById("example"); 

Definition and Use

The GetElementById () method returns an element with an ID of the specified value.

This method is one of the most common methods in the HTML DOM and is used almost every time you want to change an item in your document or get information.

Returns null if there are no items with the specified ID.

The ID must be unique within a page. However, if there are multiple elements with the specified identifier, the getElementById () method returns the first element in the source code.

EXAMPLE-1

Document.getElementById()

HTML

<html>
<head>
  <title>getElementById</title>
</head>
<body>
  <p id="example">Text</p>
  <button onclick="changeColor('blue');">blue</button>
  <button onclick="changeColor('red');">red</button>
</body>
</html>

JavaScript

function changeColor(newColor) {
  var elem = document.getElementById('example');
  elem.style.color = newColor;
}

EXAMPLE-2

Document.getElementById()

JavaScript

<script type="text/javascript">  
function getcube(){  
var number=document.getElementById("number").value;  
alert(number*number*number);  
}  
</script>  
<form>  
Enter No:<input type="text" id="number" name="number"/><br/>  
<input type="button" value="cube" onclick="getcube()"/>  
</form>  

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: