JavaScript HTML DOM
Through the HTML DOM, you can access all the elements of a JavaScript HTML document.
HTML DOM (Document Object model)
When a Web page is loaded, the browser creates a Document object model for the page.
With the programmable object model, JavaScript has the ability to create dynamic HTML.
JavaScript can change all HTML elements in a page
JavaScript can change all HTML attributes in a page
JavaScript can change all CSS styles in a page
JavaScript can react to all the events in the page
Finding HTML elements
Typically, with JavaScript, you need to manipulate HTML elements.
In order to do this, you must first find the element. There are three ways to do this:
Find HTML elements by ID
Find HTML elements by tag name
Find HTML elements by class name
Find HTML elements by ID
The simplest way to find HTML elements in the DOM is by using the ID of the element.
This example finds the id= "Intro" element:
Instance
var X=document.getelementbyid ("Intro");
If the element is found, the method returns the element in the form of an object (in X).
If the element is not found, the X will contain null.
Find HTML elements with tag names
This example finds the element id= "main" and then finds all the <p> elements in the id= "main" element:
Instance
var X=document.getelementbyid ("main");
var y=x.getelementsbytagname ("P");
Find HTML elements by class name
This example uses the Getelementsbyclassname function to find the elements of the class= "Intro":
Instance
var x=document.getelementsbyclassname ("Intro");
JavaScript HTML DOM-changing HTML
The HTML DOM allows JavaScript to change the contents of an HTML element.
Changing the HTML output stream
JavaScript is able to create dynamic HTML content:
Today's date is: Sat 16:35:50 gmt+0800 (China Standard Time)
In JavaScript, document.write () can be used to write content directly to the HTML output stream.
Instance
<! DOCTYPE html>
<body>
<script>
document.write (Date ());
</script>
</body>
Never use document.write () after the document has finished loading. This overwrites the document.
Change HTML Content
The simplest way to modify HTML content is to use the InnerHTML property.
To change the contents of an HTML element, use this syntax:
document.getElementById (ID). innerhtml= new HTML
This example changes the contents of the <p> element:
Instance
<body>
<p id= "P1" >hello world!</p>
<script>
document.getElementById ("P1"). innerhtml= "new text!";
</script>
</body>
This example changes the contents of the Instance
<! DOCTYPE html>
<body>
<script>
var Element=document.getelementbyid ("header");
Element.innerhtml= "new title";
</script>
</body>
Example Explanation:
The above HTML document contains the We use the HTML DOM to get the id= "header" element
JavaScript changes the contents of this element (InnerHTML)
Changing HTML Properties
To change the attributes of an HTML element, use this syntax:
document.getElementById (ID). attribute= new Attribute value
This example changes the SRC attribute of the element:
Instance
<! DOCTYPE html>
<body>
<script>
document.getElementById ("image"). src= "Landscape.jpg";
</script>
</body>
Example Explanation:
The above HTML document contains the elements of the id= "image"
We use the HTML DOM to get the elements of the id= "image"
JavaScript changes the attributes of this element (change "smiley.gif" to "landscape.jpg")
JavaScript HTML DOM-changing CSS
The
HTML DOM allows JavaScript to change the style of HTML elements.
Change HTML style
to change the style of an HTML element, use this syntax:
document.getElementById (ID). style.property= new Style
The example below will change <p> Element's style:
Instance
<! DOCTYPE html>
<meta charset= "Utf-8";
<title> Rookie Tutorial (runoob.com ) </title>
<body>
<p id= "P1" >hello world!</p>
<p id= "P2" > Hello world!</p>
<script>
document.getElementById ("P2"). style.color= "Blue";
document.getElementById ("P2"). style.fontfamily= "Arial";
document.getElementById ("P2"). style.fontsize= "larger";
</script>
<p> The above paragraphs are modified by script. </p>
</body>
Using Events
The HTML DOM allows us to execute code by triggering events.
such as the following events:
element is clicked.
Page loading is complete.
The input box is modified.
In the following chapters, you will learn more about events.
This example changes the style of the HTML element of the id= "ID1" when the user taps the button:
Instance
<! DOCTYPE html>
<body>
<H1 id= "Id1" > My title 1<button type= "button"
onclick= "document.getElementById (' Id1 '). style.color= ' Red '" >
Dot Me!</button>
</body>
How to make an element invisible (example:)
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title> Rookie Tutorial (runoob.com) </title>
<body>
<p id= "P1" > This is a paragraph. </p>
<input type= "button" value= "hidden text" onclick= "document.getElementById (' P1 '). style.visibility= ' Hidden '"/>
<input type= "button" value= "Display text" onclick= "document.getElementById (' P1 '). style.visibility= ' Visible '/>
</body>
The
JavaScript HTML DOM event
HTML DOM gives JavaScript the ability to react to HTML events.
Reacting to Events
We can execute JavaScript when an event occurs, such as when a user clicks on an HTML element.
to execute code when a user taps an element, add JavaScript code to an HTML event property:
Onclick=javascript
HTML Event Example:
When the user clicks the mouse
when the page is loaded
When the image is loaded
when the mouse moves to the element
when the input field is changed
when the user triggers the key when the HTML form is submitted
in this case, when the user clicks on the Instance
<! DOCTYPE html>
<body>
</body>
This example calls a function from the event handler:
Instance
<! DOCTYPE html>
<script>
function changetext (id)
{
Id.innerhtml= "ooops!";
}
</script>
<body>
</body>
If you want to assign an event to an HTML element, you can use the event properties.
Instance
To assign the OnClick event to the button element:
<button onclick= "displaydate ()" > Point here </button>
In the example above, the function named Displaydate will be executed when the button is clicked.
Use HTML DOM to assign events
HTML DOM allows you to use JavaScript to assign events to HTML elements
<body>
<p> Click the button to execute <em>displaydate () </em> function .</p>
<button id= "Mybtn" > Point here </button>
<script>
document.getElementById ("Mybtn"). Onclick=function () {displaydate ()};
function Displaydate () {
document.getElementById ("Demo"). Innerhtml=date ();
}
</script>
<p id= "Demo" ></p>
</body>
In the example above, a function named Displaydate is assigned to the HTML element of id= "MYBTN".
The JavaScript function will be executed when the button is clicked.
OnLoad and OnUnload Events
The onload and OnUnload events are triggered when the user enters or leaves the page.
The OnLoad event can be used to detect the browser type and browser version of the visitor and to load the correct version of the Web page based on that information.
The onload and OnUnload events can be used to process cookies.
<body onload= "checkcookies ()" >
<script>
function Checkcookies () {
if (navigator.cookieenabled==true) {
Alert ("Cookies available")
}
else{
Alert ("Cookies are not available")
}
}
</script>
<p> Popup-Indicates whether the browser cookie is available. </p>
</body>
onchange Events
OnChange events are often used in conjunction with validation of input fields.
Here is an example of how to use onchange. The uppercase () function is called when the user changes the contents of the input field.
Instance
<script>
function MyFunction () {
var X=document.getelementbyid ("FName");
X.value=x.value.touppercase ();
}
</script>
<body>
Enter your name: <input type= "text" id= "fname" onchange= "MyFunction ()" >
<p> when you leave the input box, the function is triggered and the lowercase letter is converted to uppercase. </p>
</body>
onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when a user moves the mouse over an HTML element or moves out of an element.
Instance
A simple example of onmouseover-onmouseout:
<body>
<div onmouseover= "MOver (This)" onmouseout= "Mout (This)" style= "Background-color: #D94A38; width:120px;height:20px ;p adding:40px; " >mouse over me</div>
<script>
function MOver (obj) {
Obj.innerhtml= "Thank You"
}
function Mout (obj) {
Obj.innerhtml= "Mouse over Me"
}
</script>
</body>
OnMouseDown, onmouseup, and onclick events
OnMouseDown, onmouseup, and onclick form all parts of the mouse click event. First, when the mouse button is clicked, the OnMouseDown event is triggered, and when the mouse button is released, the OnMouseUp event is triggered, and the onclick event is triggered when the mouse click is completed.
JavaScript HTML DOM EventListener
AddEventListener () method
Instance
To trigger a listener event when the user taps the button:
<body>
<p> The instance uses the AddEventListener () method to add a click event to the button. </p>
<button id= "Mybtn" > Point me </button>
<p id= "Demo" ></p>
<script>
document.getElementById ("Mybtn"). AddEventListener ("click", Displaydate);
function Displaydate () {
document.getElementById ("Demo"). InnerHTML = Date ();
}
</script>
</body>
The AddEventListener () method is used to add an event handle to the specified element.
The event handle added by the AddEventListener () method does not overwrite an existing event handle.
You can add multiple event handles to an element.
You can add multiple event handles of the same type to the same element, such as: Two "click" Events.
You can add event snooping to any DOM object, not just HTML elements. Such as: Window object.
The AddEventListener () method makes it easier to control events (bubbling and capturing).
When you use the AddEventListener () method, JavaScript is detached from the HTML markup and is more readable, and you can add event listeners without controlling HTML markup.
You can use the RemoveEventListener () method to remove the listener from the event.
Grammar
Element.addeventlistener (event, function, usecapture);
The first parameter is the type of event (such as "click" or "MouseDown").
The second parameter is a function that is called after the event is triggered.
The third parameter is a Boolean value that describes whether the event is bubbling or capturing. This parameter is optional.
Note: Do not use the "on" prefix. For example, use "click" instead of "onclick".
To add an event handle to the original element
Instance
"Hello world!" pops up when the user clicks on an element:
Element.addeventlistener ("click", Function () {alert ("Hello world!");})
You can use the function name to refer to an external function:
Instance
"Hello world!" pops up when the user clicks on an element:
Element.addeventlistener ("click", MyFunction);
function MyFunction () {
Alert ("Hello world!");
}
Add multiple event handles to the same element
The AddEventListener () method allows multiple events to be added to the same element without overwriting an existing event:
Instance
<body>
<p> The instance uses the AddEventListener () method to add two click events to the same button. </p>
<button id= "Mybtn" > Point me </button>
<script>
var x = document.getElementById ("mybtn");
X.addeventlistener ("click", MyFunction);
X.addeventlistener ("click", Someotherfunction);
function MyFunction () {
Alert ("Hello world!")
}
function Someotherfunction () {
Alert ("Function executed!")
}
</script>
</body>
You can add different types of events to the same element:
Instance
<body>
The <p> instance uses the AddEventListener () method to add multiple events to the same button. </p>
<button id= "Mybtn" > Point me </button>
<p id= "Demo" ></p>
<script>
var x = document.getElementById ("mybtn");
X.addeventlistener ("MouseOver", myFunction);
X.addeventlistener ("click", Mysecondfunction);
X.addeventlistener ("Mouseout", mythirdfunction);
function MyFunction () {
document.getElementById ("Demo"). InnerHTML + = "Moused over!<br>"
}
function Mysecondfunction () {
document.getElementById ("Demo"). InnerHTML + = "clicked!<br>"
}
function Mythirdfunction () {
document.getElementById ("Demo"). InnerHTML + = "Moused out!<br>"
}
</script>
</body>
To add an event handle to a Window object
The AddEventListener () method allows you to add event listeners to HTML DOM objects, such as HTML elements, HTML documents, and Window objects. or other expense event object such as: XMLHttpRequest object.
Instance
Add an event listener when the user resets the window for large hours:
Window.addeventlistener ("Resize", function () {
document.getElementById ("Demo"). InnerHTML = Sometext;
});
Passing parameters
When passing parameter values, use the anonymous function to invoke the function with parameters:
Instance
Element.addeventlistener ("click", Function () {myFunction (P1, p2);});
Event bubbling or event capture?
There are two ways of event delivery: bubbling and capturing.
Event passing defines the order in which element events are triggered. If you insert the <p> element into the <div> element and the user taps the <p> element, which element's "click" event is first triggered?
In bubbling, an inner element's event is triggered first, and then an external element is triggered, that is: The <p> element's Click event is triggered first, and then the <div> element's Click event is triggered.
In a capture, an event of an external element is first triggered before the event of the inner element is triggered, that is: The <div> element's Click event is triggered first, and then the <p> element's Click event is triggered.
The AddEventListener () method can specify the "usecapture" parameter to set the delivery type:
AddEventListener (event, function, usecapture);
The default is False, which is the bubbling pass, when the value is true, and the event uses capture delivery.
Instance
document.getElementById ("Mydiv"). AddEventListener ("Click", MyFunction, True);
RemoveEventListener () method
The RemoveEventListener () method removes the event handle added by the AddEventListener () method:
Instance
Element.removeeventlistener ("MouseMove", myFunction);
JavaScript HTML DOM Elements (nodes)
Create a new HTML element
To add a new element to the HTML DOM, you must first create the element (the element node), and then append the element to an existing element.
Instance
<div id= "Div1" >
<p id= "P1" > This is a paragraph. </p>
<p id= "P2" > this is another paragraph. </p>
</div>
<script>
var para=document.createelement ("P");
var Node=document.createtextnode ("This is a new paragraph. ");
Para.appendchild (node);
var Element=document.getelementbyid ("Div1");
Element.appendchild (para);
</script>
Example Analysis:
This code creates a new <p> element:
var para=document.createelement ("P");
To add text to the <p> element, you must first create a text node. This piece of code creates a text node:
var Node=document.createtextnode ("This is a new paragraph. ");
Then you must append the text node to the <p> element:
Para.appendchild (node);
Finally, you must append this new element to an existing element.
This code finds an existing element:
var Element=document.getelementbyid ("Div1");
The following code adds a new element after an existing element:
Element.appendchild (para);
Delete an existing HTML element
The following code demonstrates how to delete an element:
Instance
<div id= "Div1" >
<p id= "P1" > This is a paragraph. </p>
<p id= "P2" > this is another paragraph. </p>
</div>
<script>
var Parent=document.getelementbyid ("Div1");
var Child=document.getelementbyid ("P1");
Parent.removechild (child);
</script>
Instance parsing
This HTML document contains <div> elements with two child nodes (two <p> elements):
<div id= "Div1" >
<p id= "P1" > This is a paragraph. </p>
<p id= "P2" > this is another paragraph. </p>
</div>
Find the element that id= "DIV1":
var Parent=document.getelementbyid ("Div1");
Find the <p> elements of Id= "P1":
var Child=document.getelementbyid ("P1");
To remove a child element from the parent element:
Parent.removechild (child);
It would be nice to be able to delete an element without referencing the parent element.
But I'm sorry. The DOM needs to be clear about the element you need to delete, and its parent element.
This is a common solution: find the child element that you want to delete, and then use its ParentNode property to find the parent element:
var Child=document.getelementbyid ("P1");
Child.parentNode.removeChild (child);
A simple introduction to JavaScript HTML DOM