DOM Methods

HTML DOM methods are the actions that you can perform on HTML Elements.

HTML DOM properties are the values of HTML Elements that you can set or modify.


The DOM Programming Interface

HTML DOM can be accessed or used with JavaScript and with other programming languages.

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

property is a value that you can get or set (like modifying the content of an HTML element).

method is an action you can perform (like addition or deletion of a HTML element).

The following example modifies the content of the <p> element with id=”test”:

Input:-
<html>
<body>
<p id="test"></p>
<script>
document.getElementById("test").innerHTML = "Hello Document!";
</script>
</body>
</html>

Output:-


Important Methods

Some important methods of document object are given below:

MethodDescription
write(“string”)writes the given string on the document.
writeln(“string”)writes the given string on the document with newline at the end.
getElementById()returns the html element having the given id value.
getElementsByName()returns all the html elements having the given name value.
getElementsByTagName()returns all the html elements having the given tag name.
getElementsByClassName()returns all the html elements having the given class name.

Accessing field value by document object

In the below example, we are going to get the value of input text entered by user. Here, we are using document.myform.name.value to get the value of name field.

Here, document is the root element that represents the html document.

  • myform is the name of the form.
  • name is the attribute name of the input text.
  • value is the property, that returns the value of the input text entered by user.

Let’s see the below simple example of document object that outputs the name with welcome message.

Input:-
<html>
	<head>
		<script type="text/javascript">  
		function getvalue(){  
		var name=document.myform.demo.value;  
		alert("Welcome: "+name);  
		}  
	</script>  
	</head>
<body>
	<form name="myform">  
		Enter Name:<input type="text" name="demo"/>  
		<input type="button" onclick="getvalue()" value="click here"/>  
	</form> 
</body>
</html>

Output (before name enter and click):-

Output (after name enter and click):-