HTML DOM

What is the HTML DOM?

The HTML DOM is an Object Model for HTML. It defines:

  • HTML elements as objects
  • Properties for all HTML elements
  • Methods for all HTML elements
  • Events for all HTML elements

The HTML DOM is an API (Programming Interface) for JavaScript:

  • JavaScript can add/change/remove HTML elements
  • JavaScript can add/change/remove HTML attributes
  • JavaScript can add/change/remove CSS styles
  • JavaScript can react to HTML events
  • JavaScript can add/change/remove HTML events

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Finding HTML Elements

When you want to access HTML elements with JavaScript, you have to find the elements first.

There are a couple of ways to do this:

  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by CSS selectors
  • Finding HTML elements by HTML object collections
Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

    <p id="intro"></p>
    <p id="demo"></p>
    var a = document.getElementById("intro");
    document.getElementById("demo").innerHTML=a   //[object HTMLParagraphElement]

If the element is found, the method will return the element as an object (in myElement).

If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name
var x = document.getElementsByTagName("p");
Finding HTML elements by class name
var x = document.getElementsByClassName("intro");
Finding HTML elements by CSS selectors

If you want to find all HTML elements that matches a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

var x = document.querySelectorAll("p.intro");
Finding HTML elements by HTML object collections
<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>
<p id="demo"></p> 
<script>
    document.getElementById("demo").innerHTML =
        "Number of anchors are: " + document.anchors.length;  //3
</script>
  • document.anchors
  • document.forms
  • document.images
  • document.links
  • document.scripts
With the object model, what can JavaScrip do?

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

HTML DOM Methods

The DOM Programming Interface

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).

document.getElementById("demo").innerHTML = "Hello World!";
//getElementById is a method, while innerHTML is a property.

HTML DOM Document

Finding HTML Elements
MethodDescription
document.getElementById(id)Find an element by element id
document.getElementsByTagName(name)Find elements by tag name
document.getElementsByClassName(name)Find elements by class name

Changing HTML Elements
PropertyDescription
element.innerHTML = new html contentChange the inner HTML of an element
element.attribute = new valueChange the attribute value of an HTML element
element.style.property = new styleChange the style of an HTML element
MethodDescription
element.setAttribute*(attribute, value)*Change the attribute value of an HTML element
Adding and Deleting Elements
MethodDescription
document.createElement(element)Create an HTML element
document.removeChild(element)Remove an HTML element
document.appendChild(element)Add an HTML element
document.replaceChild(new, old)Replace an HTML element
document.write(text)Write into the HTML output stream
Adding Events Handlers
MethodDescription
document.getElementById(id).onclick = function(){code}Adding event handler code to an onclick event

HTML DOM - Changing HTML

Changing the HTML Output Stream

JavaScript can create dynamic HTML content:

Date: Sat May 09 2020 10:37:32 GMT+0800 (中国标准时间)

document.write() can be used to write directly to the HTML output stream:

document.write(Date());

Never use document.write() after the document is loaded. It will overwrite the document.

Changing HTML Content
document.getElementById("p1").innerHTML = "New text!";
Changing the Value of an Attribute
//To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = new value
document.getElementById("myImage").src = "landscape.jpg";

HTML DOM - Changing CSS

//To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
document.getElementById("p2").style.color = "blue";
Using Events

The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when “things happen” to HTML elements:

  • An element is clicked on
  • The page has loaded
  • Input fields are changed
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
<!-- How to make an element invisible. Do you want to show the element or not? -->
<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>
<input type="button" value="Hide text" onclick="document.getElementById('p1').style.visibility='hidden'">
<input type="button" value="Show text" onclick="document.getElementById('p1').style.visibility='visible'">

HTML DOM Animation

<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>
function myMove() {
  var elem = document.getElementById("animate");   
  var pos = 0;
  var id = setInterval(frame, 1);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.top = pos + "px"; 
      elem.style.left = pos + "px"; 
    }
  }
}

HTML DOM Events

Examples of HTML events:

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
<!-- a function is called from the event handler    called 被调用 -->
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
  id.innerHTML = "Ooops!";
}
</script>
//Assign an onclick event to a button element
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
The 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 check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

The onload and onunload events can be used to deal with cookies.

<body onload="checkCookies()">

<p id="demo"></p>

<script>
function checkCookies() {
  var text = "";
  if (navigator.cookieEnabled == true) {
    text = "Cookies are enabled.";
  } else {
    text = "Cookies are not enabled.";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
The onchange Event

The onchange event is often used in combination with validation of input fields.

<script>
function myFunction() {
  var x = document.getElementById("fname");
  x.value = x.value.toUpperCase();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
The onmouseover and onmouseout Events
<div onmouseover="mOver(this)" onmouseout="mOut(this)" 
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
  obj.innerHTML = "Thank You"
}

function mOut(obj) {
  obj.innerHTML = "Mouse Over Me"
}
</script>
The onmousedown, onmouseup Events
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
  obj.style.backgroundColor = "#1ec5e5";
  obj.innerHTML = "Release Me";
}

function mUp(obj) {
  obj.style.backgroundColor="#D94A38";
  obj.innerHTML="Thank You";
}
</script>
<!-- Change the color of an element when the cursor moves over it.-->
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text
</h1>

The addEventListener() method

//Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
  • The addEventListener() method attaches an event handler to the specified element.
  • The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
  • You can add many event handlers to one element.
  • You can add many event handlers of the same type to one element, i.e two “click” events.
  • You can add event listeners to any DOM object not only HTML elements. i.e the window object.
  • The addEventListener() method makes it easier to control how the event reacts to bubbling.
  • When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
  • You can easily remove an event listener by using the removeEventListener() method.
Syntax
element.addEventListener(event, function, useCapture);
  • The first parameter is the type of the event (like “click” or “mousedown” or any other HTML DOM Event.)
  • The second parameter is the function we want to call when the event occurs.
  • The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.

Note that you don’t use the “on” prefix for the event; use “click” instead of “onclick”.

Add Many Event Handlers to the Same Element

The addEventListener() method allows you to add many events to the same element, without overwriting existing events:

element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);

You can add events of different types to the same element:

element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Add an Event Handler to the window Object

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

//resizing this browser window to trigger the "resize" event handler.
window.addEventListener("resize", function(){    
  document.getElementById("demo").innerHTML = sometext;
});
Passing Parameters

When passing parameter values, use an “anonymous function” that calls the specified function with the parameters:

var p1 = 5;
var p2 = 7;

document.getElementById("myBtn").addEventListener("click", function() {
  myFunction(p1, p2);
});

function myFunction(a, b) {
  var result = a * b;
  document.getElementById("demo").innerHTML = result;
}
Event Bubbling or Event Capturing?

There are two ways of event propagation in the HTML DOM, bubbling and capturing.

Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element’s “click” event should be handled first?

In bubbling the inner most element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.

In capturing the outer most element’s event is handled first and then the inner: the <div> element’s click event will be handled first, then the <p> element’s click event.

With the addEventListener() method you can specify the propagation type by using the “useCapture” parameter

// false is bubbling
document.getElementById("myP1").addEventListener("click", function() {
  alert("You clicked the white element!");
}, false);

document.getElementById("myDiv1").addEventListener("click", function() {
  alert("You clicked the orange element!");
}, false);

// true is capturing
document.getElementById("myP2").addEventListener("click", function() {
  alert("You clicked the white element!");
}, true);

document.getElementById("myDiv2").addEventListener("click", function() {
  alert("You clicked the orange element!");
}, true);
The removeEventListener() method

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:

<h2>JavaScript removeEventListener()</h2>

<div id="myDIV">
  <p>This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.</p>
  <p>Click the button to remove the div's event handler.</p>
  <button onclick="removeHandler()" id="myBtn">Remove</button>
</div>

<p id="demo"></p>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = Math.random();
}

function removeHandler() {
  document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}

HTML DOM Navigation

According to the W3C HTML DOM standard, everything in an HTML document is a node

Navigating Between Nodes

You can use the following node properties to navigate between nodes with JavaScript:

  • parentNode
  • childNodes[*nodenumber*]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling
Child Nodes and Node Values

A common error in DOM processing is to expect an element node to contain text.

Example:

<title id="demo">DOM Tutorial</title>

The element node <title> (in the example above) does not contain text.

It contains a text node with the value “DOM Tutorial”.

The value of the text node can be accessed by the node’s innerHTML property:

var myTitle = document.getElementById("demo").innerHTML;

Accessing the innerHTML property is the same as accessing the nodeValue of the first child:

var myTitle = document.getElementById("demo").firstChild.nodeValue;

Accessing the first child can also be done like this:

var myTitle = document.getElementById("demo").childNodes[0].nodeValue;
DOM Root Nodes

There are two special properties that allow access to the full document:

  • document.body - The body of the document
  • document.documentElement - The full document
The nodeName Property

The nodeName property specifies the name of a node.

read-only property returns the name of the current Node as a string.

  • nodeName is read-only
  • nodeName of an element node is the same as the tag name
  • nodeName of an attribute node is the attribute name
  • nodeName of a text node is always text
  • nodeName of the document node is always document
<h1 id="id01">My First Page</h1>
<p id="id02"></p>

<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;
//My First Page
//H1
</script>

Note: nodeName always contains the uppercase tag name of an HTML element.

The nodeValue Property

The nodeValue property specifies the value of a node.

  • nodeValue for element nodes is null
  • nodeValue for text nodes is the text itself
  • nodeValue for attribute nodes is the attribute value
The nodeType Property

The nodeType property is read only. It returns the type of a node.

The most important nodeType properties are:

NodeTypeExample
ELEMENT_NODE1<h1 class=“heading”>W3Schools</h1>
ATTRIBUTE_NODE2class = “heading” (deprecated)
TEXT_NODE3W3Schools
COMMENT_NODE8
DOCUMENT_NODE9The HTML document itself (the parent of )
DOCUMENT_TYPE_NODE10<!Doctype html>

Type 2 is deprecated in the HTML DOM (but works). It is not deprecated in the XML DOM.

HTML DOM Elements (Nodes)

Creating New HTML Elements (Nodes)

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

<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 new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
</script>
Creating new HTML Elements - insertBefore()

The appendChild() method in the previous example, appended the new element as the last child of the parent.

If you don’t want that you can use the insertBefore() method:

<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 new.");
para.appendChild(node);

var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para, child);
</script>
Removing Existing HTML Elements

To remove an HTML element, use the remove() method:

<div>
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
var elmnt = document.getElementById("p1");
elmnt.remove();
</script>
Replacing HTML Elements

To replace an element to the HTML DOM, use the replaceChild() method:

<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 new.");
para.appendChild(node);

var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值