Dom &Events
Selecting Element
All HTML elements are objects. And as we know every object has properties and methods.
The document object has methods that allow you to select the desired HTML element.
These three methods are the most commonly used for selecting HTML elements:
//finds element by id
document.getElementById(id)
//finds elements by class name
document.getElementsByClassName(name)
//finds elements by tag name
document.getElementsByTagName(name)複製程式碼
Each element in the DOM has a set of properties and methods that provide information about their relationships in the DOM:
element.childNodes returns an array of an element's child nodes.
element.firstChild returns the first child node of an element.
element.lastChild returns the last child node of an element.
element.hasChildNodes returns true if an element has any child nodes, otherwise false.
element.nextSibling returns the next node at the same tree level.
element.previousSibling returns the previous node at the same tree level.
element.parentNode returns the parent node of an element.
Changing Style
The style of HTML elements can also be changed using JavaScript.
All style attributes can be accessed using the style object of the element.
For example:
<div id="demo" style="width:200px">some text</div>
<script>
var x = document.getElementById("demo");
x.style.color = "6600FF";
x.style.width = "100px";
</script>複製程式碼
Creating Elements
Use the following methods to create new nodes:
element.cloneNode() clones an element and returns the resulting node.
document.createElement(element) creates a new element node.
document.createTextNode(text) creates a new text node.
For example:
var node = document.createTextNode("Some new text");複製程式碼
This will create a new text node, but it will not appear in the document until you append it to an existing element with one of the following methods:
element.appendChild(newNode) adds a new child node to an element as the last child node.
element.insertBefore(node1, node2) inserts node1 as a child before node2.
Example:
<div id ="demo">some content</div>
<script>
//creating a new paragraph
var p = document.createElement("p");
var node = document.createTextNode("Some new text");
//adding the text to the paragraph
p.appendChild(node);
var div = document.getElementById("demo");
//adding the paragraph to the div
div.appendChild(p);
</script>複製程式碼
Removing Elements
To remove an HTML element, you must select the parent of the element and use the removeChild(node) method.
For example:
<div id="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
複製程式碼
Replacing Elements
To replace an HTML element, the element.replaceChild(newNode, oldNode) method is used.
For example:
<div id="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.replaceChild(p, child);
</script>複製程式碼
Events
Corresponding events can be added to HTML elements as attributes.
For example: <p onclick="someFunc()">some text</p>
The onload and onunload events are triggered when the user enters or leaves the page. These can be useful when performing actions after the page is loaded.<body onload="doSomething()">
Similarly, the window.onload event can be used to run code after the whole page is loaded.
window.onload = function() {
//some code
}複製程式碼
The onchange event is mostly used on textboxes. The event handler gets called when the text inside the textbox changes and focus is lost from the element.For example:
<input type="text" id="name" onchange="change()">
<script>
function change() {
var x = document.getElementById("name");
x.value= x.value.toUpperCase();
}
</script>複製程式碼
Event Listeners
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 also add many event handlers of the same type to one element, i.e., two "click"
events.element.addEventListener(event, function, useCapture);複製程式碼
The first parameter is the event's type (like "click" or "mousedown").
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, and will be described in the next lesson.
Note that you don't use the "on" prefix for this event; use "click" instead of "onclick".
Example:
element.addEventListener("click", myFunction);
element.addEventListener("mouseover", myFunction);
function myFunction() {
alert("Hello World!");
}複製程式碼
This adds two event listeners to the element.
We can remove one of the listeners:element.removeEventListener("mouseover", myFunction);
Let's create an event handler that removes itself after being executed:
<button id="demo">Start</button>
<script>
var btn = document.getElementById("demo");
btn.addEventListener("click", myFunction);
function myFunction() {
alert(Math.random());
btn.removeEventListener("click", myFunction);
}
</script>複製程式碼
After clicking the button, an alert with a random number displays and the event listener is removed.
Internet Explorer version 8 and lower do not support the addEventListener() and removeEventListener() methods. However, you can use the document.attachEvent() method to attach event handlers in Internet Explorer.
Event Propagation
There are two ways of event propagation in the HTML DOM: bubbling and capturing.
Event propagation allows for the definition of 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 innermost element's event is handled first and then the outer element's event is handled. The <p> element's click event is handled first, followed by the <div> element's click event.
In capturing, the outermost element's event is handled first and then the inner. The <div> element's click event is handled first, followed by the <p> element's click event.
Capturing goes down the DOM.
Bubbling goes up the DOM.
Capturing vs. Bubbling
The addEventListener() method allows you to specify the propagation type with the "useCapture" parameter.addEventListener(event, function, useCapture)
The default value is false, which means the bubbling propagation is used; when the value is set to true, the event uses the capturing propagation.
//Capturing propagation
elem1.addEventListener("click", myFunction, true);
//Bubbling propagation
elem2.addEventListener("click", myFunction, false);複製程式碼
This is particularly useful when you have the same event handled for multiple elements in the DOM hierarchy.