Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I access document properties using Legacy DOM method in JavaScript?
To access document properties using Legacy DOM methods in JavaScript, you can use various built-in properties and collections that provide information about the document structure and content.
Common Legacy DOM Properties
The Legacy DOM provides several properties to access document information:
-
document.title- Gets the document title -
document.URL- Gets the complete URL -
document.forms- Collection of all forms -
document.images- Collection of all images -
document.links- Collection of all links
Example
<html>
<head>
<title>Document Title</title>
<script>
function myFunc() {
var ret = document.title;
alert("Document Title : " + ret);
var ret = document.URL;
alert("Document URL : " + ret);
var ret = document.forms[0];
alert("Document First Form : " + ret);
var ret = document.forms[0].elements[1];
alert("Second element : " + ret);
}
</script>
</head>
<body>
<h1 id="title">This is main title</h1>
<p>Click the following to see the result:</p>
<form name="FirstForm">
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
<form name="SecondForm">
<input type="button" value="Don't ClickMe"/>
</form>
</body>
</html>
Accessing Form Elements
You can access forms and their elements using index numbers or names:
<script> // Access forms by index var firstForm = document.forms[0]; var secondForm = document.forms[1]; // Access forms by name var namedForm = document.forms["FirstForm"]; // Access form elements var firstElement = document.forms[0].elements[0]; var buttonElement = document.forms[0].elements["button"]; </script>
Other Legacy DOM Collections
Besides forms, you can access other document collections:
<script>
// Get number of forms
var formCount = document.forms.length;
alert("Number of forms: " + formCount);
// Get document domain
var domain = document.domain;
alert("Document domain: " + domain);
// Get last modified date
var lastMod = document.lastModified;
alert("Last modified: " + lastMod);
</script>
Browser Compatibility
Legacy DOM methods are supported across all browsers, including older versions. However, modern DOM methods like querySelector() and getElementById() are preferred for new development due to better performance and flexibility.
Conclusion
Legacy DOM properties provide direct access to document elements and information. While still functional, modern DOM methods offer more precise element selection and better performance for contemporary web development.
