The document discusses the Document Object Model (DOM), which defines a standard for accessing and modifying HTML documents as objects in a programming interface. The DOM represents an HTML document as nodes and objects that can be manipulated, allowing JavaScript and other programming languages to dynamically access and update content, structure, and styling of a document. Key DOM objects include the Document object representing the HTML document, Window and Navigator objects providing information about the browser window and user's browser, and form, image, and other objects corresponding to HTML elements.
The document discusses the Document Object Model (DOM), which defines a standard for accessing and modifying HTML documents as objects in a programming interface. The DOM represents an HTML document as nodes and objects that can be manipulated, allowing JavaScript and other programming languages to dynamically access and update content, structure, and styling of a document. Key DOM objects include the Document object representing the HTML document, Window and Navigator objects providing information about the browser window and user's browser, and form, image, and other objects corresponding to HTML elements.
The document discusses the Document Object Model (DOM), which defines a standard for accessing and modifying HTML documents as objects in a programming interface. The DOM represents an HTML document as nodes and objects that can be manipulated, allowing JavaScript and other programming languages to dynamically access and update content, structure, and styling of a document. Key DOM objects include the Document object representing the HTML document, Window and Navigator objects providing information about the browser window and user's browser, and form, image, and other objects corresponding to HTML elements.
The document discusses the Document Object Model (DOM), which defines a standard for accessing and modifying HTML documents as objects in a programming interface. The DOM represents an HTML document as nodes and objects that can be manipulated, allowing JavaScript and other programming languages to dynamically access and update content, structure, and styling of a document. Key DOM objects include the Document object representing the HTML document, Window and Navigator objects providing information about the browser window and user's browser, and form, image, and other objects corresponding to HTML elements.
Download as PPTX, PDF, TXT or read online from Scribd
Download as pptx, pdf, or txt
You are on page 1of 29
Unit 2
Java Script DOM
DOM Every web page resides inside a browser window which can be considered as an object. A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document. Window object − Top of the hierarchy. It is the outmost element of the object hierarchy. Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. Form object − Everything enclosed in the <form>...</form> tags sets the form object. Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes. Here is a simple hierarchy of a few important objects − There are several DOMs in existence. The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images. The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers. The W3C DOM standard is separated into 3 different parts: Core DOM - standard model for all document types XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features. With the object model, JavaScript gets all the power it needs to create dynamic HTML: JavaScript can change all the HTML elements in the page JavaScript can change all the HTML attributes in the page JavaScript can change all the CSS styles in the page JavaScript can remove existing HTML elements and attributes JavaScript can add new HTML elements and attributes JavaScript can react to all existing HTML events in the page JavaScript can create new HTML events in the page What is the HTML DOM? The HTML DOM is a standard object model and programming interface for HTML. It defines: The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML elements In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. The HTML DOM can be accessed 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. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element). <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> In the example above, getElementById is a method, while innerHTML is a property. JavaScript Window Navigator The window.navigator object contains information about the visitor's browser. The window.navigator object can be written without the window prefix. Some examples: navigator.appName navigator.appCodeName navigator.platform Navigator Cookie Enabled: The property cookieEnabled returns true if cookies are enabled, otherwise false. <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Cookies Enabled is " + navigator.cookieEnabled; </script> The properties appName and appCodeName return the name of the browser: <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Name is " + navigator.appName + ". Code name is " + navigator.appCodeName; </script> Objects in HTML Just like real world objects, HTML objects have a number of properties that determine the behavior of that object. It can be referenced as: ObjectName.PropertyName textbox.name Properties determine the state of an object. While building interactive web pages an objects' properties need to be set dynamically. Methods of an object are used to set or get a value of an objects’ property. ObjectName.MethodName The javascript objects are: navigator : for browser information window: To access a browser window or a frame within the window. It does not require window prefix when refereeing to its properties and methods. document: To access the document currently loaded into a window. location: To represent a URL history: To maintain a history of the URL’s accessed within a window. event: To access information about the occurrence of an event. EVENT: provide constants that are used to identify events. screen: To access information about client’s screen in which the current browser is running. How browser handles Document Object The browser creates one array in memory per HTML object in document. If these HTML objects actually contains in HTML page then these array will hold indexed elements, which will point to the context area in the memory where the HTML objects are. Otherwise the array will exists, but will be empty. If there are multiple similar objects each array will have multiple elements or indexes. images[0], images[1] Once the context area is known, you can set or get properties of object. The HTML DOM Document In the HTML DOM object model, the document object represents your web page. The document object is the owner of all other objects in your web page. If you want to access objects in an HTML page, you always start with accessing the document object. Below are some examples of how you can use the document object to access and manipulate HTML. Finding HTML Elements:
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name document.getElementsByClassName() Find elements by class name Changing HTML attribute:
element.innerHTML= Change the inner HTML of an element
element.attribute= Change the attribute of an HTML element element.setAttribute(attribute,value) Change the attribute of an HTML element element.style.property= Change the style of an HTML element Adding and Deleting Elements:
document.createElement() Create an HTML element
document.removeChild() Remove an HTML element document.appendChild() Add an HTML element document.replaceChild() Replace an HTML element document.write(text) Write into the HTML output stream Adding Events Handlers:
document.getElementById(id).oncli Adding event handler code to an
ck=function(){code} onclick event Finding HTML Objects: The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.
document.anchors Returns all <a> elements that have a name attribute
document.applets Returns all <applet> elements (Deprecated in HTML5) document.baseURI Returns the absolute base URI of the document document.body Returns the <body> element document.cookie Returns the document's cookie document.doctype Returns the document's doctype document.documentElement Returns the <html> element document.documentMode Returns the mode used by the browser document.documentURI Returns the URI of the document document.domain Returns the domain name of the document server document.domConfig Obsolete. Returns the DOM configuration document.embeds Returns all <embed> elements document.forms Returns all <form> elements document.head Returns the <head> element document.images Returns all <img> elements document.implementation Returns the DOM implementation document.inputEncoding Returns the document's encoding (character set) document.lastModified Returns the date and time the document was updated document.links Returns all <area> and <a> elements that have a href attribute document.readyState Returns the (loading) status of the document document.referrer Returns the URI of the referrer (the linking document) document.scripts Returns all <script> elements document.strictErrorChecking Returns if error checking is enforced document.title Returns the <title> element document.URL Returns the complete URL of the document Exercise 1: Use the getElementById method to find the <p> element, and change its text to "Good Job!". <p id="demo">Use the DOM to change my text!</p> <script> document.getElementById(“demo”).innerHTML=“Good Job!”; </script> Exercise 2:Click the button to create a P element with some text. Var par= Document.createElement(“P”); Var t = Document.createTextNode(“This is Para”); Par.appendChile(t); Document.body.appendChild(par); User Defined Objects All user-defined objects and built-in objects are descendants of an object called Object. The new Operator The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions. var employee = new Object(); var books = new Array("C++", "Perl", "Java"); var day = new Date("August 15, 1947"); The Object() Constructor A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword. Using External Javascript File Sometimes the Javascript that you create in an HTML document may extend to tens and hundreds of lines. This may affect the readability of HTML document. Also sometimes you want same script in several web pages. In such situation, you can create an external script file . After creating file, you need to link it with HTML by using the <script> tag. <script src=“filename.js”></script> Handling Exceptions Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). Logical Errors Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program. The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors. The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch. The throw statement allows you to create a custom error. Technically you can raise (throw) an exception. The exception can be a JavaScript String, a Number, a Boolean or an Object. The finally statement lets you execute code, after try and catch, regardless of the result. History Object The history object contains the URLs visited by the user (within a browser window). The history object is part of the window object and is accessed through the window.history property. Properties: length : Returns the number of URLs in the history list Methods:
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list go() Loads a specific URL from the history list Dense Array A dense array allows programmers to efficiently declare an array when the initial values of the array is known beforehand. Dense arrays are supported in all major browsers. var myarray=new Array("one","two","three") The above is what's called a dense array, since it compresses the declaration and initialization of an array into one step. As you can see, we directly passed in the values of the array as parameters . var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday") var montharray=new rray("January","February","March","April","May", "June","July","August","September","October","November","Decembe r") //write out the final results document.write("<b>"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+"</b>") one more important thing about array in JavaScript that JavaScript allows different types values or object in one array like this: var DiffArray=new Array(35, "Author", 5 , 7, "Code", null, true, false, new array(2,3)) DiffArray[0] = 35 DiffArray[1] = “Author” DiffArray[2] = 5 DiffArray[3] = 7 DiffArray[4] = “Code” DiffArray[5] = null DiffArray[6] = true DiffArray[7] = false DiffArray[8] = a new dense array that consist two elements 2 and 3 var1 = DiffArray[8][0]; var2 = DiffArray[8][1]; Insert Row and Column Use methods insertRow(index) insertCell(index)