[Go to site: main page, start]

0% found this document useful (0 votes)
78 views107 pages

Understanding JavaScript HTML DOM

The Document Object Model (DOM) is a programming interface for HTML and XML documents that defines their logical structure and allows for dynamic access and manipulation using JavaScript. The HTML DOM represents web pages as a tree of objects, enabling JavaScript to change elements, attributes, styles, and respond to events. Various methods, such as getElementById, getElementsByTagName, and querySelectorAll, are available for finding and manipulating HTML elements within the DOM.

Uploaded by

Prabin Magar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views107 pages

Understanding JavaScript HTML DOM

The Document Object Model (DOM) is a programming interface for HTML and XML documents that defines their logical structure and allows for dynamic access and manipulation using JavaScript. The HTML DOM represents web pages as a tree of objects, enabling JavaScript to change elements, attributes, styles, and respond to events. Various methods, such as getElementById, getElementsByTagName, and querySelectorAll, are available for finding and manipulating HTML elements within the DOM.

Uploaded by

Prabin Magar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript HTML DOM

Introduction:
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup
language) documents. It defines the logical structure of documents and the way a document is accessed and
manipulated.

Note: It is called as a Logical structure because DOM doesn’t specify any relationship between objects.

DOM is a way to represent the webpage in the structured hierarchical way so that it will become easier for
programmers and users to glide through the document. With DOM, we can easily access and manipulate tags,
IDs, classes, Attributes or Elements using commands or methods provided by Document object.

With the HTML DOM, JavaScript can access and change all the elements of an HTML document. The HTML DOM
(Document Object Model) - When a web page is loaded, the browser creates a Document Object Model of
the page. The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

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 DOM? The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for
accessing documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content, structure, and style of a
document."

The W3C DOM standard is separated into 3 different parts: (1) Core DOM - standard model for all document
types (2) XML DOM - standard model for XML documents (3) HTML DOM - standard model for HTML documents

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 DOM Programming Interface

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). The following example changes the content
(the innerHTML) of the <p> element with id="demo":

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>

In the example above, getElementById is a method, while innerHTML is a property.

JavaScript HTML DOM Document - The HTML DOM document object is the owner of all other objects in your
web page.

The HTML DOM Document Object - The document object represents your web page. If you want to access
any element 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.

JavaScript HTML DOM Elements

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first.
There are several ways to do this:

Finding HTML Element by Id - The easiest way to find an HTML element in the DOM, is by using the element
id. This example finds the element with id="intro":

var myElement = [Link]("intro");


[Link]("demo").innerHTML =
"The text from the intro paragraph is " + [Link]; // The text from the intro
paragraph is Hello World!

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. Another example:

<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
// get the element
let elem = [Link]('elem');
// make its background red
[Link] = 'red';
</script>

Also, there’s a global variable named by id that references the element:

<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
// elem is a reference to DOM-element with id="elem"
[Link] = 'red';
// id="elem-content" has a hyphen inside, so it can't be a variable name
// ...but we can access it using square brackets: window['elem-content']
</script>

…That’s unless we declare a JavaScript variable with the same name, then it takes precedence:

<div id="elem"></div>
<script>
let elem = 5; // now elem is 5, not a reference to <div id="elem">
alert(elem); // 5
</script>
Please don’t use id-named global variables to access elements - The browser tries to help us by mixing
namespaces of JS and DOM. That’s fine for simple scripts, inlined into HTML, but generally isn’t a good thing.
There may be naming conflicts. Also, when one reads JS code and doesn’t have HTML in view, it’s not obvious
where the variable comes from.

Here in the tutorial we use id to directly reference an element for brevity, when it’s obvious where the element
comes from. In real life [Link] is the preferred method.

The id must be unique - The id must be unique. There can be only one element in the document with the
given id. If there are multiple elements with the same id, then the behavior of methods that use it is
unpredictable, e.g. [Link] may return any of such elements at random. So please stick to
the rule and keep id unique.

Only [Link], not [Link] - The method getElementById that can be


called only on document object. It looks for the given id in the whole document.

Finding HTML Elements by Tag Name - This example finds all <p> elements:

var x = [Link]("p");
[Link]("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML; // The text in first paragraph
(index 0) is: Hello World!

Example - In the following example, getElementsByTagName() starts from a particular parent element and
searches top-down recursively through the DOM from that parent element, building a collection of all
descendant elements which match the tag name parameter.

This demonstrates both [Link]() and the functionally


identical [Link](), which starts the search at a specific element within the DOM tree.

Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular
parent (either the document itself or one of two nested <div> elements).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>getElementsByTagName example</title>
<script>
function getAllParaElems() {
var allParas = [Link]('p');
var num = [Link];
alert('There are ' + num + ' paragraph in this document');
}
function div1ParaElems() {
var div1 = [Link]('div1');
var div1Paras = [Link]('p');
var num = [Link];
alert('There are ' + num + ' paragraph in #div1');
}
function div2ParaElems() {
var div2 = [Link]('div2');
var div2Paras = [Link]('p');
var num = [Link];
alert('There are ' + num + ' paragraph in #div2');
}
</script>
</head>
<body style="border: solid green 3px">
<p>Some outer text</p>
<p>Some outer text</p>
<div id="div1" style="border: solid blue 3px">
<p>Some div1 text</p>
<p>Some div1 text</p>
<p>Some div1 text</p>
<div id="div2" style="border: solid red 3px">
<p>Some div2 text</p>
<p>Some div2 text</p>
</div>
</div>

<p>Some outer text</p>


<p>Some outer text</p>
<button > show all p elements in document</button><br />
<button > show all p elements in div1 element</button><br />
<button > show all p elements in div2 element</button>
</body>
</html>

This example finds the element with id="main", and then finds all <p> elements inside "main":

<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>
<p id="demo"></p>
<script>
var x = [Link]("main");
var y = [Link]("p");
[Link]("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML; // The first paragraph
(index 0) inside “main” is: The DOM is very userful.
</script>

Finding HTML Elements by Class Name - If you want to find all HTML elements with the same class name,
use getElementsByClassName(). This example returns a list of all elements with class="intro".

<p>Hello World!</p>
<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>
<p id="demo"></p>
<script>
var x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; // The first paragraph
(index 0) with class = “intro”: The DOM is very userful.
</script>

Examples
Get all elements that have a class of 'test': [Link]('test')
Get all elements that have both the 'red' and 'test' classes: [Link]('red test')
Get all elements that have a class of 'test', inside of an element that has the ID of 'main':
[Link]('main').getElementsByClassName('test')
Get the first element with a class of 'test', or undefined if there is no matching element:
[Link]('test')[0]

We can also use methods of [Link] on any HTMLCollection by passing the HTMLCollection as the
method's this value. Here we'll find all div elements that have a class of 'test':

var testElements = [Link]('test');


var testDivs = [Link](testElements, function(testElement){
return [Link] === 'DIV';
});

Get the first element whose class is 'test' - This is the most commonly used method of operation.

<html>
<body>
<div id="parent-id">
<p>hello world 1</p>
<p class="test">hello world 2</p>
<p>hello world 3</p>
<p>hello world 4</p>
</div>
<script>
var parentDOM = [Link]("parent-id");
var test = [Link]("test"); // a list of matching elements,
*not* the element itself
[Link](test); //HTMLCollection[1]
var testTarget = [Link]("test")[0]; // the first element, as
we wanted
[Link](testTarget); //<p class="test">hello world 2</p>
</script>
</body>
</html>

Finding elements by class name does not work in Internet Explorer 8 and earlier versions.

Finding HTML Elements by CSS Selectors - If you want to find all HTML elements that match a specified CSS
selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method. This
example returns a list of all <p> elements with class="intro".

<p>Hello World!</p>
<p class="intro">The DOM is very useful.</p>
<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>
<p id="demo"></p>
<script>
var x = [Link]("[Link]");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML; // The first paragraph
(index 0) with class = “intro”: The DOM is very useful.
</script>

Obtaining a list of matches - To obtain a NodeList of all of the <p> elements in the document:
var matches = [Link]("p");
This example returns a list of all <div> elements within the document with a class of either note or alert:
var matches = [Link]("[Link], [Link]");

Here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and
which are located inside a container whose ID is test.
var container = [Link]("#test");
var matches = [Link]("[Link] > p");

This example uses an attribute selector to return a list of the <iframe> elements in the document that contain
an attribute named data-src:
var matches = [Link]("iframe[data-src]");

Here, an attribute selector is used to return a list of the list items contained within a list whose ID
is userlist which have a data-active attribute whose value is 1:
var container = [Link]("#userlist");
var matches = [Link]("li[data-active='1']");
Accessing the matches - Once the NodeList of matching elements is returned, you can examine it just like
any array. If the array is empty (that is, its length property is 0), then no matches were found. Otherwise, you
can simply use standard array notation to access the contents of the list. You can use any common looping
statement, such as:

var highlightedItems = [Link](".highlighted");


[Link](function(userItem) {
deleteUser(userItem);
});

User notes - querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might
lead to unexpected results.

Consider this HTML, with its three nested <div> blocks.


<div class="outer">
<div class="select">
<div class="inner">
</div>
</div>
</div>
var select = [Link]('.select');
var inner = [Link]('.outer .inner');
[Link]; // 1, not 0!

In this example, when selecting .outer .inner in the context the <div> with the class select, the element with the
class .inner is still found, even though .outer is not a descendant of the base element on which the search is
performed (.select). By default, querySelectorAll() only verifies that the last element in the selector is within the
search scope.

The :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the base
element:

var select = [Link]('.select');


var inner = [Link](':scope .outer .inner');
[Link]; // 0

By far, the most versatile method, [Link](css) returns all elements inside elem matching the
given CSS selector.
Here we look for all <li> elements that are last children:

<ul>
<li>The</li>
<li>test</li>
</ul>
<ul>
<li>has</li>
<li>passed</li>
</ul>
<script>
let elements = [Link]('ul > li:last-child');
for (let elem of elements) {
alert([Link]); // "test", "passed"
}
</script>

This method is indeed powerful, because any CSS selector can be used.

Can use pseudo-classes as well - Pseudo-classes in the CSS selector like :hover and :active are also
supported. For instance, [Link](':hover') will return the collection with elements that the
pointer is over now (in nesting order: from the outermost <html> to the most nested one).
querySelector - The call to [Link](css) returns the first element for the given CSS selector. In
other words, the result is the same as [Link](css)[0], but the latter is looking for all elements and
picking one, while [Link] just looks for one. So it’s faster and also shorter to write.

Matches - Previous methods were searching the DOM.


The [Link](css) does not look for anything, it merely checks if elem matches the given CSS-selector. It
returns true or false. The method comes in handy when we are iterating over elements (like in an array or
something) and trying to filter out those that interest us. For instance:

<a href="[Link]
<a href="[Link]
<script>
// can be any collection instead of [Link]
for (let elem of [Link]) {
if ([Link]('a[href$="zip"]')) {
alert("The archive reference: " + [Link] );
}
}
</script>

Closest - Ancestors of an element are: parent, the parent of parent, its parent and so on. The ancestors
together form the chain of parents from the element to the top. The method [Link](css) looks the nearest
ancestor that matches the CSS-selector. The elem itself is also included in the search. In other words, the
method closest goes up from the element and checks each of parents. If it matches the selector, then the
search stops, and the ancestor is returned. For instance:

<h1>Contents</h1>
<div class="contents">
<ul class="book">
<li class="chapter">Chapter 1</li>
<li class="chapter">Chapter 1</li>
</ul>
</div>
<script>
let chapter = [Link]('.chapter'); // LI
alert([Link]('.book')); // UL
alert([Link]('.contents')); // DIV
alert([Link]('h1')); // null (because h1 is not an ancestor)
</script>

[Link]()

The Document method querySelector() returns the first Element within the document that matches the
specified selector, or group of selectors. If no matches are found, null is returned.

Syntax: element = [Link](selectors);

Escaping special characters - To match against an ID or selectors that do not follow standard CSS syntax (by
using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). As
the backslash is also an escape character in JavaScript, if you are entering a literal string, you must escape
it twice (once for the JavaScript string, and another time for querySelector()):

<div id="foo\bar"></div>
<div id="foo:bar"></div>
<script>
[Link]('#foo\bar'); // "#fooar" (\b is the backspace control character)
[Link]('#foo\bar'); // Does not match anything
[Link]('#foo\\bar'); // "#foo\bar"
[Link]('#foo\\\\bar'); // "#foo\\bar"
[Link]('#foo\\\\bar'); // Match the first div
[Link]('#foo:bar'); // Does not match anything
[Link]('#foo\\:bar'); // Match the second div
</script>

Finding the first element matching a class - In this example, the first element in the document with the
class "myclass" is returned: var el = [Link](".myclass");

A more complex selector - Selectors can also be really powerful, as demonstrated in the following example.
Here, the first <input> element with the name "login" (<input name="login"/>) located inside a <div> whose
class is "user-panel main" (<div class="user-panel main">) in the document is returned:

var el = [Link]("[Link] input[name='login']");

Negation - As all CSS selector strings are valid, you can also negate selectors:
var el = [Link]("[Link]-panel:not(.main) input[name='login']");

This will select every input with a parent div with the user-panel class but not the main class.

Live collections

All methods "getElementsBy*" return a live collection. Such collections always reflect the current state of the
document and “auto-update” when it changes. In the example below, there are two scripts.

1. The first one creates a reference to the collection of <div>. As of now, its length is 1.

2. The second scripts runs after the browser meets one more <div>, so its length is 2.

<div>First div</div>
<script>
let divs = [Link]('div');
alert([Link]); // 1
</script>
<div>Second div</div>
<script>
alert([Link]); // 2
</script>

In contrast, querySelectorAll returns a static collection. It’s like a fixed array of elements. If we use it instead,
then both scripts output 1:

<div>First div</div>
<script>
let divs = [Link]('div');
alert([Link]); // 1
</script>
<div>Second div</div>
<script>
alert([Link]); // 1
</script>

Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm1", in the forms collection, and displays all element values:

<h2>Finding HTML Elements Using [Link]</h2>


<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>
<p>Click "Try it" to display the value of each element in the form.</p>
<button it</button>
<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]["frm1"];
var text = "";
var i;
for (i = 0; i < [Link] ;i++) {
text += [Link][i].value + "<br>";
}
[Link]("demo").innerHTML = text; // Donald
Duck
Submit
}
</script>

The following HTML objects (and object collections) are also accessible:

[Link]
<h2>Finding HTML Elements Using [Link]</h2>
<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>
[Link]("demo").innerHTML =
"Number of anchors are: " +
[Link]; // 3
</script>

[Link]
<p id="demo"></p>
<script>
alert([Link]);
</script>

[Link]
<p id="demo"></p>
<script>
alert([Link]);
</script>

[Link]
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Number of embeds: " + [Link]; // Number of embeds: 0
</script>

[Link]
<form action="">
First name: <input type="text" name="fname" value="Donald">
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Number of forms: " + [Link]; // Number of forms: 1
</script>

[Link]
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
[Link]; // [object HTMLHeadElement]
</script>

[Link]
<img src="pic_htmltree.gif" width="486" height="266">
<img src="pic_navigate.gif" width="362" height="255">
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Number of images: " + [Link]; // Number of images: 2
</script>

[Link]
<p>
<a href="/html/[Link]">HTML</a>
<br>
<a href="/css/[Link]">CSS</a>
</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Number of links: " + [Link]; // Number of links: 2
</script>

[Link]
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Number of scripts: " + [Link]; // Number of scripts: 1
</script>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>W3Schools Demo</title>
</head>
<body>
<h2>Finding HTML Elements Using [Link]</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"The title of this document is: " + [Link]; // The title of this document is:
W3Schools Demo
</script>
</body>
</html>

JavaScript HTML DOM - Changing HTML

The HTML DOM allows JavaScript to change the content of HTML elements.

Changing the HTML Output Stream - JavaScript can create dynamic HTML content: Date: Mon Mar 23
2020 09:38:38 GMT+0545 (Nepal Time)

In JavaScript, [Link]() can be used to write directly to the HTML output stream:
[Link](Date());

Changing HTML Content - The easiest way to modify the content of an HTML element is by using
the innerHTML property. To change the content of an HTML element, use this syntax:
[Link](id).innerHTML = new HTML

This example changes the content of a <p> element:


<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New text!";
</script>

Example explained: 1) The HTML document above contains a <p> element with id="p1" 2) We use the HTML
DOM to get the element with id="p1" 3) A JavaScript changes the content (innerHTML) of that element to "New
text!"

This example changes the content of an <h1> element:

<h1 id="id01">Old Heading</h1>


<script>
var element = [Link]("id01");
[Link] = "New Heading";
</script>
<p>JavaScript changed "Old Heading" to "New Heading".</p>

Example explained: 1) The HTML document above contains an <h1> element with id="id01" 2) We use the
HTML DOM to get the element with id="id01" 3) A JavaScript changes the content (innerHTML) of that element
to "New Heading"

Changing the Value of an Attribute - To change the value of an HTML attribute, use this syntax:
[Link](id).attribute = new value

This example changes the value of the src attribute of an <img> element:
<img id="myImage" src="[Link]">
<script>
[Link]("myImage").src = "[Link]";
</script>

Example explained: 1) The HTML document above contains an <img> element with id="myImage" 2) We use
the HTML DOM to get the element with id="myImage" 3) A JavaScript changes the src attribute of that element
from "[Link]" to "[Link]"

Access a Style Object - The Style object can be accessed from the head section of the document, or from
specific HTML element(s). Accessing style object(s) from the head section of the document:

<style>
body {
background-color: yellow;
color: red;
}
</style>
</head>
<body>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("STYLE")[0];
[Link]("demo").innerHTML = [Link];
}
</script>

Accessing a specified element's style object:

<h1 id="myH1" style="color:red">My Header</h1>


<p>Click the button to get the style property of
the H1 element.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("myH1").[Link];
[Link]("demo").innerHTML = x;
}
</script>

Create a Style Object - You can create a <style> element by using the [Link]() method:

<button >it</button
<p>The created style element contains css
declarations that will change the font
properties of this document.</p>
<script>
function myFunction() {
var x = [Link]("STYLE");
var t = [Link]("body {font: 20px verdana;}");
[Link](t);
[Link](x);
}
</script>

You can also set the style properties of an existing element:


[Link]("myH1").[Link] = "red";

JavaScript HTML DOM Animation

A Basic Web Page - To demonstrate how to create HTML animations with JavaScript, we will use a simple web
page:
<h1>My First JavaScript Animation</h1>
<div id="animation">My animation will go here</div>

Create an Animation Container - All animations should be relative to a container element.


<div id ="container">
<div id ="animate">My animation will go here</div>
</div>

Style the Elements

The container element should be created with style = "position: relative".

The animation element should be created with style = "position:


absolute".

<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<body>
<h2>My First JavaScript Animation</h2>
<div id="container">
<div id="animate"></div>
</div>

Animation Code - JavaScript animations are done by programming gradual changes in an element's style. The
changes are called by a timer. When the timer interval is small, the animation looks continuous. The basic code
is:

var id = setInterval(frame, 5);


function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}

Create the Animation Using JavaScript

<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>

<script>
function myMove() {
var elem = [Link]("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
[Link] = pos + "px";
[Link] = pos + "px";
}
}
}
</script>

JavaScript HTML DOM Events

HTML DOM allows JavaScript to react to HTML events:

Reacting to Events - A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
> In this example, the content of the <h1> element is changed when a user clicks on it:
<h1 = 'Ooops!'">Click on this text!</h1>

In this example, a function is called from the event handler:

<h1 on this text!</h1>


<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>

HTML Event Attributes - To assign events to HTML elements you can use event attributes.

<button time


is?</button>
<script>
function displayDate() {
[Link]("demo").innerHTML =
Date();
}
</script>
<p id="demo"></p>

Assign Events Using the HTML DOM - The HTML DOM allows you to assign events to HTML elements using
JavaScript:

Assign an onclick event to a button element:

<button id="myBtn">Try it</button>


<p id="demo"></p>
<script>
[Link]("myBtn"). >displayDate;
function displayDate() {
[Link]("demo").innerHTML =
Date();
}
</script>

In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn". The
function will be executed when the button is clicked.

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 ><p id="demo"></p>
<script>
function checkCookies() {
var text = "";
if ([Link] == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
[Link]("demo").innerHTML = text;
}
</script>
</body>

The onchange Event - The onchange event is often used in combination with validation of input fields. Below
is an example of how to use the onchange. The upperCase() function will be called when a user changes the
content of an input field.

<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
}
</script>
</head>
<body>

Enter your name: <input type="text" id="fname" >
<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 - The onmouseover and onmouseout events can be used to
trigger a function when the user mouses over, or out of, an HTML element:

<div >
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
[Link] = "Thank You"
}
function mOut(obj) {
[Link] = "Mouse Over Me"
}
</script>

The onmousedown, onmouseup and onclick Events - The onmousedown, onmouseup, and onclick events
are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then,
when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is
completed, the onclick event is triggered.

<div >
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
[Link] = "#1ec5e5";
[Link] = "Release Me";
}
function mUp(obj) {
[Link]="#D94A38";
[Link]="Thank You";
}
</script>

JavaScript HTML DOM EventListener

The addEventListener() method

Add an event listener that fires when a user clicks a button:

<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
[Link]("myBtn").addEventListener("click", displayDate);
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>

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: [Link](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 an Event Handler to an Element

Alert "Hello World!" when the user clicks on an element:

<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<script>
[Link]("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
</script>

You can also refer to an external "named" function:

Alert "Hello World!" when the user clicks on an element:

<p>This example uses the addEventListener() method to execute a function when a user clicks on
a button.</p>
<button id="myBtn">Try it</button>
<script>
[Link]("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
</script>

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:
<p>This example uses the addEventListener() method to add two click events to the same
button.</p>
<button id="myBtn">Try it</button>
<script>
var x = [Link]("myBtn");
[Link]("click", myFunction);
[Link]("click", someOtherFunction);
function myFunction() {
alert ("Hello World!");
}
function someOtherFunction() {
alert ("This function was also executed!");
}
</script>

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

[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("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.

Add an event listener that fires when a user resizes the window:

<p>This example uses the


addEventListener() method on the window
object.</p>
<p>Try resizing this browser window to
trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
[Link]("resize", function(){
[Link]("demo").innerHTML = [Link]();
});
</script>

Passing Parameters

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

<p>Click the button to perform a calculation.</p>


<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var p1 = 5;
var p2 = 7;
[Link]("myBtn").addEventListener("click", function() {
myFunction(p1, p2);
});
function myFunction(a, b) {
var result = a * b;
[Link]("demo").innerHTML = result; // 35
}
</script>
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:

addEventListener(event, function, useCapture);

The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses
the capturing propagation.

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv1, #myDiv2 {
background-color: coral;
padding: 50px;
}
#myP1, #myP2 {
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
</head>
<body>
<h2>JavaScript addEventListener()</h2>
<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>
<div id="myDiv2">
<h2>Capturing:</h2>
<p id="myP2">Click me!</p>
</div>

<script>
[Link]("myP1").addEventListener("click", function() {
alert("You clicked the white element!");
}, false);
[Link]("myDiv1").addEventListener("click", function() {
alert("You clicked the orange element!");
}, false);
[Link]("myP2").addEventListener("click", function() {
alert("You clicked the white element!");
}, true);
[Link]("myDiv2").addEventListener("click", function() {
alert("You clicked the orange element!");
}, true);
</script>
</body>
</html>
The removeEventListener() method

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

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<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 id="myBtn">Remove</button>
</div>
<p id="demo"></p>

<script>
[Link]("myDIV").addEventListener("mousemove", myFunction);
function myFunction() {
[Link]("demo").innerHTML = [Link]();
}
function removeHandler() {
[Link]("myDIV").removeEventListener("mousemove", myFunction);
}
</script>
</body>
</html>

Note: The addEventListener() and removeEventListener() methods are not supported in IE 8 and earlier
versions. However, for these specific browser versions, you can use the attachEvent() method to attach an event
handlers to the element, and the detachEvent() method to remove it:

[Link](event, function);
[Link](event, function);

Cross-browser solution:

var x = [Link]("myBtn");
if ([Link]) { // For all major browsers, except IE 8 and earlier
[Link]("click", myFunction);
} else if ([Link]) { // For IE 8 and earlier versions
[Link]("onclick", myFunction);
}

JavaScript HTML DOM Navigation

With the HTML DOM, you can navigate the node


tree using node relationships.
DOM Nodes - According to the W3C HTML DOM standard, everything in an HTML document is a node:

 The entire document is a document node


 Every HTML element is an element node
 The text inside HTML elements are text nodes
 Every HTML attribute is an attribute node (deprecated)
 All comments are comment nodes

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript. New nodes can be created, and
all nodes can be modified or deleted.

Node Relationships - The nodes in the node tree have a hierarchical relationship to each other. The terms
parent, child, and sibling are used to describe the relationships.

 In a node tree, the top node is called the root (or root node)
 Every node has exactly one parent, except the root (which has no parent)
 A node can have a number of children
 Siblings (brothers or sisters) are nodes with the same parent

<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>

From the HTML above you can read:

 <html> is the root node


 <html> has no parents
 <html> is the parent of <head> and <body>
 <head> is the first child of <html>
 <body> is the last child of <html>

and:

 <head> has one child: <title>


 <title> has one child (a text node): "DOM Tutorial"
 <body> has two children: <h1> and <p>
 <h1> has one child: "DOM Lesson one"
 <p> has one child: "Hello world!"
 <h1> and <p> are siblings

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.

<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 =
[Link]("demo").innerHTML;

Accessing the innerHTML property is the same as accessing the nodeValue of the first child: var myTitle =
[Link]("demo").[Link];

Accessing the first child can also be done like this: var myTitle =
[Link]("demo").childNodes[0].nodeValue;

All the (3) following examples retrieves the text of an <h1> element and copies it into a <p> element:

<h1 id="id01">My First Page</h1>


<p id="id02"></p>
<script>
[Link]("id02").innerHTML =
[Link]("id01").innerHTML;
</script>
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
[Link]("id02").innerHTML =
[Link]("id01").[Link];
</script>
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
[Link]("id02").innerHTML =
[Link]("id01").childNodes[0].nodeValue;
</script>

InnerHTML - In this tutorial we use the innerHTML property to retrieve the content of an HTML element.
However, learning the other methods above is useful for understanding the tree structure and the navigation of
the DOM.

DOM Root Nodes - There are two special properties that allow access to the full document:

 [Link] - The body of the document


 [Link] - The full document

The nodeName Property - The nodeName property specifies the name of a node.

 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

Example

<h1 id="id01">My First Page</h1>


<p id="id02"></p>
<script>
[Link]("id02").innerHTML =
[Link]("id01").nodeName;
</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.

<h1 id="id01">My First Page</h1>


<p id="id02"></p>
<script>
[Link]("id02").innerHTML =
[Link]("id01").nodeType;
</script>

The most important nodeType properties are:

Node Type Example

ELEMENT_NODE 1 <h1 class="heading">W3Schools</h1>

ATTRIBUTE_NODE 2 class = "heading" (deprecated)

TEXT_NODE 3 W3Schools

COMMENT_NODE 8 <!-- This is a comment -->

DOCUMENT_NODE 9 The HTML document itself (the parent of <html>)

DOCUMENT_TYPE_NODE 10 <!Doctype html>

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

JavaScript HTML DOM Elements (Nodes)

Adding and Removing Nodes (HTML Elements)

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 = [Link]("p");
var node = [Link]("This is new.");
[Link](node);
var element = [Link]("div1");
[Link](para);
</script>

Example Explained - This code creates a new <p> element: var para = [Link]("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node = [Link]("This is a new paragraph.");
Then you must append the text node to the <p> element: [Link](node);
Finally you must append the new element to an existing element.
This code finds an existing element: var element = [Link]("div1");

This code appends the new element to the existing element: [Link](para);

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 = [Link]("p");
var node = [Link]("This is new.");
[Link](node);
var element = [Link]("div1");
var child = [Link]("p1");
[Link](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>
<button Element</button>
<script>
function myFunction() {
var elmnt = [Link]("p1");
[Link]();
}
</script>

Example Explained - The HTML document contains a <div> element with two child nodes
(two <p> elements). Find the element you want to remove: var elmnt = [Link]("p1");

Then execute the remove() method on that element: [Link]();


The remove() method does not work in older browsers, see the example below on how to
use removeChild() instead.

Removing a Child Node - For browsers that does not support the remove() method, you have to find the
parent node to remove an element:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = [Link]("div1");
var child = [Link]("p1");
[Link](child);
</script>

Example Explained - This HTML document contains a <div> element with two child nodes
(two <p> elements). Find the element with id="div1": var parent = [Link]("div1");
Find the <p> element with id="p1": var child = [Link]("p1");
Remove the child from the parent: [Link](child);

Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the
parent:

var child = [Link]("p1");


[Link](child);

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 parent = [Link]("div1");
var child = [Link]("p1");
var para = [Link]("p");
var node = [Link]("This is new.");
[Link](node);
[Link](para,child);
</script>

JavaScript HTML DOM Collections

The HTMLCollection Object

The getElementsByTagName() method returns an HTMLCollection object. An HTMLCollection object is an array-


like list (collection) of HTML elements. The following code selects all <p> elements in a document:

var x = [Link]("p");

The elements in the collection can be accessed by an index number. To access the second <p> element you
can write:

<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
var myCollection =
[Link]("p");
[Link]("demo").innerHTML = "The
innerHTML of the second paragraph is: " +
myCollection[1].innerHTML;
</script>

Note: The index starts at 0.

HTML HTMLCollection Length

The length property defines the number of elements in


an HTMLCollection:

<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
var myCollection = [Link]("p");
[Link]("demo").innerHTML =
"This document contains " + [Link] + " paragraphs.";
</script>

Example explained: 1) Create a collection of all <p> elements 2) Display the length of the collection

The length property is useful when you want to loop through the elements in a collection:

Change the background color of all <p> elements:

<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button it</button>
<script>
function myFunction() {
var myCollection = [Link]("p");
var i;
for (i = 0; i < [Link]; i++) {
myCollection[i].[Link] = "red";
}
}
</script>

An HTMLCollection is NOT an array! An HTMLCollection may look like an array, but it is not. You can loop
through the list and refer to the elements with a number (just like an array). However, you cannot use array
methods like valueOf(), pop(), push(), or join() on an HTMLCollection.

JavaScript HTML DOM Node Lists

A NodeList object is a list (collection) of nodes extracted from a document. A NodeList object is almost the same
as an HTMLCollection object. Some (older) browsers return a NodeList object instead of an HTMLCollection for
methods like getElementsByClassName(). All browsers return a NodeList object for the property childNodes.
Most browsers return a NodeList object for the method querySelectorAll(). The following code selects
all <p> nodes in a document: var myNodeList = [Link]("p");

The elements in the NodeList can be accessed by an index number. To access the second <p> node you can
write:

<h2>JavaScript HTML DOM!</h2>


<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
var myNodelist = [Link]("p");
[Link]("demo").innerHTML =
"The innerHTML of the second paragraph is: " +
myNodelist[1].innerHTML;
</script>

Note: The index starts at 0.

HTML DOM Node List Length

The length property defines the number of nodes in a node list:

<h2>JavaScript HTML DOM!</h2>


<p>Hellow World!</p>
<p>Hellow Norway!</p>
<p id="demo"></p>
<script>
var myNodelist = [Link]("p");
[Link]("demo").innerHTML =
"This document contains " + [Link] + " paragraphs.";
</script>

Example explained: 1) Create a list of all <p> elements 2) Display the length of the list

The length property is useful when you want to loop through the nodes in a node list

Change the background color of all <p> elements in a node list:

<h2>JavaScript HTML DOM!</h2>


<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button it</button>
<script>
function myFunction() {
var myNodelist = [Link]("p");
var i;
for (i = 0; i < [Link]; i++) {
myNodelist[i].[Link] = "red";
}
}
</script>

The Difference Between an HTMLCollection and a NodeList

An HTMLCollection (previous chapter) is a collection of HTML elements. A NodeList is a collection of document


nodes. A NodeList and an HTML collection is very much the same thing. Both an HTMLCollection object and a
NodeList object is an array-like list (collection) of objects. Both have a length property defining the number of
items in the list (collection). Both provide an index (0, 1, 2, 3, 4, ...) to access each item like an array.

HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed
by their index number. Only the NodeList object can contain attribute nodes and text nodes.

A node list is not an array! A node list may look like an array, but it is not. You can loop through the node list
and refer to its nodes like an array. However, you cannot use Array Methods, like valueOf(), push(), pop(), or
join() on a node list.

JavaScript DOM Nodes

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>

The above HTML document can be represented by the following DOM tree:
The above diagram demonstrates the parent/child relationships between the nodes. The topmost node i.e. the
Document node is the root node of the DOM tree, which has one child, the <html> element. Whereas,
the <head> and <body> elements are the child nodes of the <html> parent node.

The <head> and <body> elements are also siblings since they are at the same level. Further, the text content
inside an element is a child node of the parent element. So, for example, "Mobile OS" is considered as a child
node of the <h1> that contains it, and so on.

Comments inside the HTML document are nodes in the DOM tree as well, even though it doesn't affect the visual
representation of the document in any way. Comments are useful for documenting the code, however, you will
rarely need to retrieve and manipulate them.

HTML attributes such as id, class, title, style, etc. are also considered as nodes in DOM hierarchy but they don't
participate in parent/child relationships like the other nodes do. They are accessed as properties of the element
node that contains them.

Each element in an HTML document such as image, hyperlink, form, button, heading, paragraph, etc. is
represented using a JavaScript object in the DOM hierarchy, and each object contains properties and methods to
describe and manipulate these objects. For example, the style property of the DOM elements can be used to get
or set the inline style of an element.

In the next few chapters we'll learn how to access individual elements on a web page and manipulate them, for
example, changing their style, content, etc. using the JavaScript program.

Tip: The Document Object Model or DOM is, in fact, basically a representation of the various components of the
browser and the current Web document (HTML or XML) that can be accessed or manipulated using a scripting
language such as JavaScript.

JavaScript DOM Selectors

Selecting DOM Elements in JavaScript - JavaScript is most commonly used to get or modify the content or
value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But,
before you can perform any action you need to find or select the target HTML element.

In the following sections, you will see some of the common ways of selecting the elements on a page and do
something with them using the JavaScript.

Selecting the Topmost Elements - The topmost elements in an HTML document are available directly
as document properties. For example, the <html> element can be accessed
with [Link] property, whereas the <head> element can be accessed
with [Link] property, and the <body> element can be accessed with [Link] property. Here's
an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Topmost Elements</title>
</head>
<body>
<script>
// Display lang attribute value of html element
alert([Link]("lang")); // Outputs: en
// Set background color of body element
[Link] = "yellow";
// Display tag name of the head element's first child
alert([Link]); // Outputs: meta
</script>
</body>
</html>

But, be careful. If [Link] is used before the <body> tag (e.g. inside the <head>), it will
return null instead of the body element. Because the point at which the script is executed, the <body> tag was
not parsed by the browser, so [Link] is truly null at that point. Let's take a look at the following
example to better understand this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS [Link] Demo</title>
<script>
alert("From HEAD: " + [Link]); // Outputs: null (since <body> is not parsed yet)
</script>
</head>
<body>
<script>
alert("From BODY: " + [Link]); // Outputs: HTMLBodyElement
</script>
</body>
</html>

Selecting Elements by ID - You can select an element based on its unique ID with
the getElementById() method. This is the easiest way to find an HTML element in the DOM tree. The following
example selects and highlight an element having the ID attribute id="mark".

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Element by ID</title>
</head>
<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
var match = [Link]("mark");
// Highlighting element's background
[Link] = "yellow";
</script>
</body>
</html>
The getElementById() method will return the element as an object if the matching element was found, or null if
no matching element was found in the document.

Note: Any HTML element can have an id attribute. The value of this attribute must be unique within a page i.e.
no two elements in the same page can have the same ID.

Selecting Elements by Class Name - Similarly, you can use the getElementsByClassName() method to select
all the elements having specific class names. This method returns an array-like object of all child elements
which have all of the given class names. Let's check out
the following example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Class
Name</title>
</head>
<body>
<p class="test">This is a paragraph of text.</p>
<div class="block test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting elements with class test
var matches = [Link]("test");
// Displaying the selected elements count
[Link]("Number of selected elements: " + [Link]);
// Applying bold style to first element in selection
matches[0].[Link] = "bold";
// Applying italic style to last element in selection
matches[[Link] - 1].[Link] = "italic";
// Highlighting each element's background through loop
for(var elem in matches) {
matches[elem].[Link] = "yellow";
}
</script>
</body>
</html>

Selecting Elements by Tag Name - You can also select HTML elements by tag name using the
getElementsByTagName() method. This method also returns an array-like object of all child elements with the
given tag name.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements by Tag Name</title>
</head>
<body>
<p>This is a paragraph of text.</p>
<div class="test">This is another paragraph of text.</div>
<p>This is one more paragraph of text.</p>
<script>
// Selecting all paragraph elements
var matches = [Link]("p");
// Printing the number of selected paragraphs
[Link]("Number of selected elements: " + [Link]);
// Highlighting each paragraph's background through loop
for(var elem in matches) {
matches[elem].[Link] = "yellow";
}
</script>
</body>
</html>

Selecting Elements with CSS Selectors - You can use the querySelectorAll() method to select elements that
matches the specified CSS selector. CSS selectors provide a very powerful and efficient way of selecting HTML
elements in a document. Please check out the CSS tutorial section to learn more about them.

This method returns a list of all the elements that matches the specified selectors. You can examine it just like
any array, as shown in the following example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Select Elements with CSS Selectors</title>
</head>
<body>
<ul>
<li>Bread</li>
<li class="tick">Coffee</li>
<li>Pineapple Cake</li>
</ul>
<script>
// Selecting all li elements
var matches = [Link]("ul li");
// Printing the number of selected li elements
[Link]("Number of selected elements: " + [Link] + "<hr>")

// Printing the content of selected li elements


for(var elem of matches) {
[Link]([Link] + "<br>");
}
// Applying line through style to first li element with class tick
matches = [Link]("ul [Link]");
matches[0].[Link] = "line-through";
</script>
</body>
</html>

Note: The querySelectorAll() method also supports CSS pseudo-classes like :first-child, :last-child, :hover, etc.
But, for CSS pseudo-elements such as ::before, ::after, ::first-line, etc. this method always returns an empty list.

JavaScript DOM Styling

Styling DOM Elements in JavaScript - You can also apply style on HTML elements to change the visual
presentation of HTML documents dynamically using JavaScript. You can set almost all the styles for the elements
like, fonts, colors, margins, borders, background images, text alignment, width and height, position, and so on.

In the following section we'll discuss the various methods of setting styles in JavaScript.

Setting Inline Styles on Elements - Inline styles are applied directly to the specific HTML element using the
style attribute. In JavaScript the style property is used to get or set the inline style of an element. The following
example will set the color and font properties of an element with id="intro".

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Set Inline Styles Demo</title>
</head>
<body>
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem = [Link]("intro");
// Appling styles on element
[Link] = "blue";
[Link] = "18px";
[Link] = "bold";
</script>
</body>
</html>

Naming Conventions of CSS Properties in JavaScript - Many CSS properties, such as font-
size, background-image, text-decoration, etc. contain hyphens (-) in their names. Since, in JavaScript hyphen is a
reserved operator and it is interpreted as a minus sign, so it is not possible to write an expression,
like: [Link]-size

Therefore, in JavaScript, the CSS property names that contain one or more hyphens are converted to
intercapitalized style word. It is done by removing the hyphens and capitalizing the letter immediately following
each hyphen, thus the CSS property font-size becomes the DOM property fontSize, border-left-
style becomes borderLeftStyle, and so on.

Getting Style Information from Elements - Similarly, you get the styles applied on the HTML elements using
the style property. The following example will get the style information from the element having id="intro".

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Get Element's Style Demo</title>
</head>
<body>
<p id="intro" style="color:red; font-size:20px;">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem = [Link]("intro");
// Getting style information from element
alert([Link]); // Outputs: red
alert([Link]); // Outputs: 20px
alert([Link]); // Outputs nothing
</script>
</body>
</html>

The style property isn't very useful when it comes to getting style information from the elements, because it
only returns the style rules set in the element's style attribute not those that come from elsewhere, such as
style rules in the embedded style sheets, or external style sheets. To get the values of all CSS properties that
are actually used to render an element you can use the [Link]() method, as shown in the
following example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Computed Style Demo</title>
<style type="text/css">
#intro {
font-weight: bold;
font-style: italic;
}
</style>
</head>
<body>
<p id="intro" style="color:red; font-size:20px;">This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
// Selecting element
var elem = [Link]("intro");
// Getting computed style information
var styles = [Link](elem);
alert([Link]("color")); // Outputs: rgb(255, 0, 0)
alert([Link]("font-size")); // Outputs: 20px
alert([Link]("font-weight")); // Outputs: 700
alert([Link]("font-style")); // Outputs: italic
</script>
</body>
</html>

Tip: The value 700 for the CSS property font-weight is same as the keyword bold. The color keyword red is same
as rgb(255,0,0), which is the rgb notation of a color.

Adding CSS Classes to Elements - You can also get or set CSS classes to the HTML elements using
the className property. Since, class is a reserved word in JavaScript, so JavaScript uses the className property
to refer the value of the HTML class attribute. The following example will show to how to add a new class, or
replace all existing classes to a <div> element having id="info".

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Add or Replace CSS Classes Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something very important!</div>
<script>
// Selecting element
var elem = [Link]("info");
[Link] = "note"; // Add or replace all classes with note class
[Link] += " highlight"; // Add a new class highlight
</script>
</body>
</html>

There is even better way to work with CSS classes. You can use the classList property to get, set or remove CSS
classes easily from an element. This property is supported in all major browsers except Internet Explorer prior to
version 10. Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS classList Demo</title>
<style>
.highlight {
background: yellow;
}
</style>
</head>
<body>
<div id="info" class="disabled">Something very important!</div>
<script>
// Selecting element
var elem = [Link]("info");
[Link]("hide"); // Add a new class
[Link]("note", "highlight"); // Add multiple classes
[Link]("hide"); // Remove a class
[Link]("disabled", "note"); // Remove multiple classes
[Link]("visible"); // If class exists remove it, if not add it
// Determine if class exist
if([Link]("highlight")) {
alert("The specified class exists on the element.");
}
</script>
</body>
</html>

JavaScript DOM Get Set Attributes

Working with Attributes - The attributes are special words used inside the start tag of an HTML element to
control the tag's behavior or provides additional information about the tag. JavaScript provides several methods
for adding, removing or changing an HTML element's attribute. In the following sections we will learn about
these methods in detail.

Getting Element's Attribute Value - The getAttribute() method is used to get the current value of a attribute
on the element. If the specified attribute does not exist on the element, it will return null. Here's an example:

<a href="[Link] target="_blank" id="myLink">Google</a>


<script>
// Selecting the element by ID attribute
var link = [Link]("myLink");
// Getting the attributes values
var href = [Link]("href");
alert(href); // Outputs: [Link]
var target = [Link]("target");
alert(target); // Outputs: _blank
</script>

JavaScript provides several different ways to select elements on a page. Please check out the JavaScript DOM
selectors chapter to learn more about them.

Setting Attributes on Elements - The setAttribute() method is used to set an attribute on the specified
element. If the attribute already exists on the element, the value is updated; otherwise a new attribute is added
with the specified name and value. The JavaScript code in the following example will add a class and
a disabled attribute to the <button> element.

<button type="button" id="myBtn">Click Me</button>


<script>
// Selecting the element
var btn = [Link]("myBtn");
// Setting new attributes
[Link]("class", "click-btn");
[Link]("disabled", "");
</script>

Similarly, you can use the setAttribute() method to update or change the value of an existing attribute on an
HTML element. The JavaScript code in the following example will update the value of the existing href attribute
of an anchor (<a>) element.

<a href="#" id="myLink">Tutorial Republic</a>


<script>
// Selecting the element
var link = [Link]("myLink");
// Changing the href attribute value
[Link]("href", "[Link]
</script>
Removing Attributes from Elements - The removeAttribute() method is used to remove an attribute from
the specified element. The JavaScript code in the following example will remove the href attribute from an
anchor element.

<a href="[Link] id="myLink">Google</a>


<script>
// Selecting the element
var link = [Link]("myLink");
// Removing the href attribute
[Link]("href");
</script>

JavaScript DOM Manipulation

In this tutorial you will learn how to manipulate elements in JavaScript.

Manipulating DOM Elements in JavaScript - Now that you've learnt how to select and style HTML DOM
elements. In this chapter we will learn how to add or remove DOM elements dynamically, get their contents, and
so on.

Adding New Elements to DOM - You can explicitly create new element in an HTML document, using
the [Link]() method. This method creates a new element, but it doesn't add it to the DOM;
you'll have to do that in a separate step, as shown in the following example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Creating a new div element
var newDiv = [Link]("div");
// Creating a text node
var newContent = [Link]("Hi, how are you doing?");
// Adding the text node to the newly created div
[Link](newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = [Link]("main");
[Link](newDiv, currentDiv);
</script>

The appendChild() method adds the new element at the end of any other children of a specified parent node.
However, if you want to add the new element at the beginning of any other children you can use
the insertBefore() method, as shown in example below:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Creating a new div element
var newDiv = [Link]("div");
// Creating a text node
var newContent = [Link]("Hi, how are you doing?");
// Adding the text node to the newly created div
[Link](newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = [Link]("main");
[Link](newDiv, currentDiv);
</script>

Getting or Setting HTML Contents to DOM - You can also get or set the contents of the HTML elements
easily with the innerHTML property. This property sets or gets the HTML markup contained within the element
i.e. content between its opening and closing tags. Checkout the following example to see how it works:
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
// Getting inner HTML conents
var contents = [Link]("main").innerHTML;
alert(contents); // Outputs inner html contents
// Setting inner HTML contents
var mainDiv = [Link]("main");
[Link] = "<p>This is <em>newly inserted</em> paragraph.</p>";
</script>

As you can see how easily you can insert new elements into DOM using the innerHTML property, but there is one
problem, the innerHTML property replaces all existing content of an element. So if you want to insert the HTML
into the document without replacing the existing contents of an element, you can use
the insertAdjacentHTML() method.

This method accepts two parameters: the position in which to insert and the HTML text to insert. The position
must be one of the following values: "beforebegin", "afterbegin", "beforeend", and "afterend". This method is
supported in all major browsers.

The following example shows the visualization of position names and how it works.

<!-- beforebegin -->


<div id="main">
<!-- afterbegin -->
<h1 id="title">Hello World!</h1>
<!-- beforeend -->
</div>
<!-- afterend -->
<script>
// Selecting target element
var mainDiv = [Link]("main");
// Inserting HTML just before the element itself, as a previous
sibling
[Link]('beforebegin', '<p>This is paragraph
one.</p>');
// Inserting HTML just inside the element, before its first child
[Link]('afterbegin', '<p>This is paragraph
two.</p>');
// Inserting HTML just inside the element, after its last child
[Link]('beforeend', '<p>This is paragraph three.</p>');
// Inserting HTML just after the element itself, as a next sibling
[Link]('afterend', '<p>This is paragraph four.</p>');
</script>

Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent
element. Also, when inserting HTML into a page, be careful not to use user input that hasn't been escaped, to
prevent XSS attacks.

Removing Existing Elements from DOM - Similarly, you can use the removeChild() method to remove a
child node from the DOM. This method also returns the removed node. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
var parentElem =
[Link]("main");
var childElem = [Link]("hint");
[Link](childElem);
</script>

It is also possible to remove the child element without exactly knowing the parent element. Simply find the child
element and use the parentNode property to find its parent element. This property returns the parent of the
specified node in the DOM tree. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
var childElem = [Link]("hint");
[Link](childElem);
</script>

Replacing Existing Elements in DOM - You can also replace an element in HTML DOM with another using
the replaceChild() method. This method accepts two parameters: the node to insert and the node to be
replaced. It has the syntax like [Link](newChild, oldChild);. Here's an example:

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple
paragraph.</p>
</div>
<script>
var parentElem =
[Link]("main");
var oldPara = [Link]("hint");
// Creating new elememt
var newPara = [Link]("p");
var newContent = [Link]("This is a new paragraph.");
[Link](newContent);
// Replacing old paragraph with newly created paragraph
[Link](newPara, oldPara);
</script>

JavaScript DOM Navigation

In this tutorial you will learn how to navigate between DOM nodes in JavaScript.

Navigating Between DOM Nodes - In the previous chapters you've learnt how to select individual elements
on a web page. But there are many occasions where you need to access a child, parent or ancestor element.

DOM node provides several properties and methods that allow you to navigate or traverse through the tree
structure of the DOM and make changes very easily. In the following section we will learn how to navigate up,
down, and sideways in the DOM tree using JavaScript.

Accessing the Child Nodes - You can use the firstChild and lastChild properties of the DOM node to access
the first and last direct child node of a node, respectively. If the node doesn't have any child element, it
returns null.

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = [Link]("main");
[Link]([Link]); // Prints: #text
var hint = [Link]("hint");
[Link]([Link]); // Prints: SPAN
</script>
Note: The nodeName is a read-only property that returns the name of the current node as a string. For
example, it returns the tag name for element node, #text for text node, #comment for comment
node, #document for document node, and so on.

If you notice the above example, the nodeName of the first-child node of the main DIV element returns #text
instead of H1. Because, whitespace such as spaces, tabs, newlines, etc. are valid characters and they form
#text nodes and become a part of the DOM tree. Therefore, since the <div> tag contains a newline before
the <h1> tag, so it will create a #text node.

To avoid the issue with firstChild and lastChild returning #text or #comment nodes, you could alternatively use
the firstElementChild and lastElementChild properties to return only the first and last element node,
respectively. But, it will not work in IE 9 and earlier.

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = [Link]("main");
alert([Link]); // Outputs: H1
[Link] = "red";
var hint = [Link]("hint");
alert([Link]); // Outputs: SPAN
[Link] = "blue";
</script>

Similarly, you can use the childNodes property to access all child nodes of a given element, where the first child
node is assigned index 0. Here's an example:

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = [Link]("main");
// First check that the element has child nodes
if([Link]()) {
var nodes = [Link];
// Loop through node list and display node name
for(var i = 0; i < [Link]; i++) {
alert(nodes[i].nodeName);
}
}
</script>

The childNodes returns all child nodes, including non-element nodes like text and comment nodes. To get a
collection of only elements, use children property instead.

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var main = [Link]("main");
// First check that the element has child nodes
if([Link]()) {
var nodes = [Link];
// Loop through node list and display node name
for(var i = 0; i < [Link]; i++) {
alert(nodes[i].nodeName);
}
}
</script>
Accessing the Parent Nodes - You can use the parentNode property to access the parent of the specified
node in the DOM tree. The parentNode will always return null for document node, since it doesn't have a parent.

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var hint = [Link]("hint");
alert([Link]); // Outputs: DIV
alert([Link]); // Outputs: #document
alert([Link]); // Outputs: null
</script>

Tip: The topmost DOM tree nodes can be accessed directly as document properties.

For example, the <html> element can be accessed with [Link] property, whereas
the <head> element can be accessed with [Link] property, and the <body> element can be accessed
with [Link] property. However, if you want to get only element nodes you can use the parentElement,
like this:

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var hint = [Link]("hint");
alert([Link]); // Outputs: DIV
[Link] = "yellow";
</script>

Accessing the Sibling Nodes - You can use the previousSibling and nextSibling properties to access the
previous and next node in the DOM tree, respectively. Here's an example:

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p><hr>
</div>
<script>
var title = [Link]("title");
alert([Link]); // Outputs: #text
var hint = [Link]("hint");
alert([Link]); // Outputs: HR
</script>

Alternatively, you can use the previousElementSibling and nextElementSibling to get the previous and next
sibling element skipping any whitespace text nodes. All these properties returns null if there is no such sibling.
Here's an example:

<div id="main">
<h1 id="title">My Heading</h1>
<p id="hint"><span>This is some text.</span></p>
</div>
<script>
var hint = [Link]("hint");
alert([Link]); // Outputs: H1
alert([Link]); // Outputs: My Heading
var title = [Link]("title");
alert([Link]); // Outputs: P
alert([Link]); // Outputs: This is some text.
</script>
The textContent property represents the text content of a node and all of its descendants.

Types of DOM Nodes - The DOM tree is consists of different types of nodes, such as elements, text,
comments, etc.

Every node has a nodeType property that you can use to find out what type of node you are dealing with. The
following table lists the most important node types:

Constant Value Description

ELEMENT_NODE 1 An element node such as <p> or <img>.

TEXT_NODE 3 The actual text of element.

COMMENT_NODE 8 A comment node i.e. <!-- some comment -->

DOCUMENT_NODE 9 A document node i.e. the parent of <html> element.

DOCUMENT_TYPE_NODE 10 A document type node e.g. <!DOCTYPE html> for HTML5 documents.

JS Browser BOM

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM) - There are no official standards for the Browser Object Model (BOM).
Since modern browsers have implemented (almost) the same methods and properties for JavaScript
interactivity, it is often referred to, as methods and properties of the BOM.

The Window Object - The window object is supported by all browsers. It represents the browser's window. All
global JavaScript objects, functions, and variables automatically become members of the window object.

Global variables are properties of the window object. Global functions are methods of the window object. Even
the document object (of the HTML DOM) is a property of the window object:
[Link]("header"); is the same as: [Link]("header");

Window Size

Two properties can be used to determine the size of the browser window. Both properties return the sizes in
pixels:

 [Link] - the inner height of the browser window (in pixels)


 [Link] - the inner width of the browser window (in pixels)

The browser window (the browser viewport) is NOT including toolbars and scrollbars.

For Internet Explorer 8, 7, 6, 5:

 [Link]
 [Link]
 or
 [Link]
 [Link]

A practical JavaScript solution (covering all browsers):

<p id="demo"></p>
<script>
var w = [Link]
|| [Link]
|| [Link];
var h = [Link]
|| [Link]
|| [Link];
var x = [Link]("demo");
[Link] = "Browser inner window width: " + w + ", height: " + h + ".";
</script>

The example displays the browser window's height and width: (NOT including toolbars/scrollbars)

Other Window Methods

Some other methods:


 [Link]() - open a new window
 [Link]() - close the current window
 [Link]() - move the current window
 [Link]() - resize the current window

JavaScript Window Screen

The [Link] object contains information about the user's screen.

Window Screen - The [Link] object can be written without the window prefix. Properties:

 [Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]

Window Screen Width - The [Link] property returns the width of the visitor's screen in pixels.

Display the width of the screen in pixels:

[Link]("demo").innerHTML = "Screen Width: " + [Link]; // Screen Width:


1366

Window Screen Height - The [Link] property returns the height of the visitor's screen in pixels.

Display the height of the screen in pixels:

[Link]("demo").innerHTML = "Screen Height: " + [Link]; // Screen


Height: 768

Window Screen Available Width - The [Link] property returns the width of the visitor's screen, in
pixels, minus interface features like the Windows Taskbar.

Display the available width of the screen in pixels:

[Link]("demo").innerHTML = "Available Screen Width: " + [Link];


// Available Screen Width: 1366

Window Screen Available Height - The [Link] property returns the height of the visitor's screen,
in pixels, minus interface features like the Windows Taskbar.

Display the available height of the screen in pixels:

[Link]("demo").innerHTML = "Available Screen Height: " + [Link];


// Available Screen Height: 728
Window Screen Color Depth - The [Link] property returns the number of bits used to display one
color. All modern computers use 24 bit or 32 bit hardware for color resolution:

 24 bits = 16,777,216 different "True Colors"


 32 bits = 4,294,967,296 different "Deep Colors"

Older computers used 16 bits: 65,536 different "High Colors" resolution. Very old computers, and old cell phones
used 8 bits: 256 different "VGA colors".

Display the color depth of the screen in bits:

[Link]("demo").innerHTML = "Screen Color Depth: " + [Link];


// Screen Color Depth: 24

The #rrggbb (rgb) values used in HTML represents "True Colors" (16,777,216 different colors)

Window Screen Pixel Depth - The [Link] property returns the pixel depth of the screen.

Display the pixel depth of the screen in bits:

[Link]("demo").innerHTML = "Screen Pixel Depth: " + [Link];


// Screen Pixel Depth: 24

For modern computers, Color Depth and Pixel Depth are equal.

JavaScript Window Location

The [Link] object can be used to get the current page address (URL) and to redirect the browser to a
new page.

Window Location - The [Link] object can be written without the window prefix. Some examples:

 [Link] returns the href (URL) of the current page


 [Link] returns the domain name of the web host
 [Link] returns the path and filename of the current page
 [Link] returns the web protocol used (http: or https:)
 [Link]() loads a new document

Window Location Href - The [Link] property returns the URL of the current page.

Display the href (URL) of the current page:

<h3>The [Link] object</h3>


<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"The full URL of this page is:<br>" + [Link]; // Page location is
[Link]
</script>

Window Location Hostname - The [Link] property returns the name of the internet host
(of the current page).

Display the name of the host:

<h3>The [Link] object</h3>


<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Page hostname is: " + [Link];
// Page hostname is [Link]
</script>

Window Location Pathname - The [Link] property returns the pathname of the current
page.

Display the path name of the current URL:

[Link]("demo").innerHTML = "Page path is " + [Link];


// Page path is /js/js_window_location.asp

Window Location Protocol - The [Link] property returns the web protocol of the page.

Display the web protocol:

[Link]("demo").innerHTML =
"Page protocol is " + [Link]; // Page protocol is https:

Window Location Port - The [Link] property returns the number of the internet host port (of
the current page).

Display the name of the host:

[Link]("demo").innerHTML = "Port number is " + [Link];


// Port number is

Most browsers will not display default port numbers (80 for http and 443 for https)

Window Location Assign - The [Link]() method loads a new document.

Load a new document:

<html>
<head>
<script>
function newDoc() {
[Link]("[Link]
}
</script>
</head>
<body>
<input type="button" value="Load new document" ></body>
</html>

JavaScript Window History

The [Link] object contains the browsers history.

Window History - The [Link] object can be written without the window prefix. To protect the privacy
of the users, there are limitations to how JavaScript can access this object. Some methods:

 [Link]() - same as clicking back in the browser


 [Link]() - same as clicking forward in the browser

Window History Back - The [Link]() method loads the previous URL in the history list. This is the same
as clicking the Back button in the browser.
Create a back button on a page:

<html>
<head>
<script>
function goBack() {
[Link]()
}
</script>
</head>
<body>
<input type="button" value="Back" ></body>
</html>

Window History Forward - The [Link]() method loads the next URL in the history list. This is the
same as clicking the Forward button in the browser.

Create a forward button on a page:

<html>
<head>
<script>
function goForward() {
[Link]()
}
</script>
</head>
<body>
<input type="button" value="Forward" ></body>
</html>

JavaScript Window Navigator

The [Link] object contains information about the visitor's browser.

Window Navigator - The [Link] object can be written without the window prefix. Some examples:

 [Link]
 [Link]
 [Link]

Browser Cookies - The cookieEnabled property returns true if cookies are enabled, otherwise false:

<h2>The Navigator Object</h2>


<p>The cookieEnabled property returns true if
cookies are enabled:</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"[Link] is " +
[Link];
</script>

Browser Application Name - The appName property returns the application name of the browser:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "[Link] is " + [Link];
</script>
Strange enough, "Netscape" is the application name for both IE11, Chrome, Firefox, and Safari.

Browser Application Code Name - The appCodeName property returns the application code name of the
browser:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "[Link] is " +
[Link];
</script>

"Mozilla" is the application code name for both Chrome, Firefox, IE, Safari, and Opera.

The Browser Engine - The product property returns the product name of the browser engine:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "[Link] is " + [Link];
</script>

Do not rely on this. Most browsers returns "Gecko" as product name !!

The Browser Version - The appVersion property returns version information about the browser:

<p id="demo"></p>
<script> [Link]("demo").innerHTML = [Link];
</script>

The Browser Agent - The userAgent property returns the user-agent header sent by the browser to the server:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link];
</script>

Warning !!!

The information from the navigator object can often be misleading, and should not be used to detect browser
versions because:

 Different browsers can use the same name


 The navigator data can be changed by the browser owner
 Some browsers misidentify themselves to bypass site tests
 Browsers cannot report new operating systems, released later than the browser

The Browser Platform - The platform property returns the browser platform (operating system):

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link];
</script>

The Browser Language - The language property returns the browser's language:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link];
</script>

Is The Browser Online? - The onLine property returns true if the browser is online:
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link];
</script>

Is Java Enabled? - The javaEnabled() method returns true if Java is enabled:

<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link]();
</script>

JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box - An alert box is often used if you want to make sure information comes through to the user. When an
alert box pops up, the user will have to click "OK" to proceed.

Syntax: [Link]("sometext");

The [Link]() method can be written without the window prefix.

<h2>JavaScript Alert</h2>
<button it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>

Confirm Box - A confirm box is often used if you want the user to verify or accept something. When a confirm
box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box
returns true. If the user clicks "Cancel", the box returns false.

Syntax: [Link]("sometext");

The [Link]() method can be written without the window prefix.

<h2>JavaScript Confirm Box</h2>


<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
[Link]("demo").innerHTML = txt;
}
</script>

Prompt Box - A prompt box is often used if you want the user to input a value before entering a page. When a
prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax: [Link]("sometext","defaultText");
The [Link]() method can be written without the window prefix.

<h2>JavaScript Prompt</h2>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:",
"Harry Potter");
if (person == null || person == "") {
txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you
today?";
}
[Link]("demo").innerHTML =
txt;
}
</script>

Line Breaks

To display line breaks inside a popup box, use a back-slash followed by the character n.

<h2>JavaScript</h2>
<p>Line-breaks in a popup box.</p>
<button are you?')">Try it</button>

JavaScript Timing Events

JavaScript can be executed in time-intervals. This is called timing events.

Timing Events - The window object allows execution of code at specified time intervals. These time intervals
are called timing events. The two key methods to use with JavaScript are:

 setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
 setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.

The setTimeout() and setInterval() are both methods of the HTML DOM Window object.

The setTimeout() Method

[Link](function, milliseconds);

The [Link]() method can be written without the window prefix. The first parameter is a function to
be executed. The second parameter indicates the number of milliseconds before execution.

Click a button. Wait 3 seconds, and the page will alert "Hello":

<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button 3000);">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
How to Stop the Execution?

The clearTimeout() method stops the execution of the function specified in setTimeout().

[Link](timeoutVariable)

The [Link]() method can be written without the window prefix. The clearTimeout() method uses
the variable returned from setTimeout():

myVar = setTimeout(function, milliseconds);


clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by calling the clearTimeout() method:

Same example as above, but with an added "Stop" button:

<p>Click "Try it". Wait 3 seconds. The page will


alert "Hello".</p>
<p>Click "Stop" to prevent the first function to
execute.</p>
<p>(You must click "Stop" before the 3 seconds are
up.)</p>
<button = setTimeout(myFunction,
3000)">Try it</button>
<button it</button>
<script>
function myFunction() {
alert("Hello");
}
</script>

The setInterval() Method

The setInterval() method repeats a given function at every given time-interval.

[Link](function, milliseconds);

The [Link]() method can be written without the window prefix. The first parameter is the function to
be executed. The second parameter indicates the length of the time-interval between each execution. This
example executes a function called "myTimer" once every second (like a digital watch).

Display the current time:

var myVar = setInterval(myTimer, 1000);


function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}

There are 1000 milliseconds in one second.

How to Stop the Execution?

The clearInterval() method stops the executions of the function specified in the setInterval() method.

[Link](timerVariable)

The [Link]() method can be written without the window prefix. The clearInterval() method uses
the variable returned from setInterval():
myVar = setInterval(function, milliseconds);
clearInterval(myVar);

Same example as above, but we have added a "Stop time" button:

<p>A script on this page starts this clock:</p>


<p id="demo"></p>
<button time</button>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
[Link]("demo").innerHTML = [Link]();
}
</script>

JavaScript Cookies

Cookies let you store user information in web pages.

What are Cookies? Cookies are data, stored in small text files, on your computer. When a web server has sent
a web page to a browser, the connection is shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":

 When a user visits a web page, his/her name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like: username = John Doe

When a browser requests a web page from a server, cookies belonging to the page are added to the request.
This way the server gets the necessary data to "remember" information about users.

None of the examples below will work if your browser has local cookies support turned off.

Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the [Link] property. With JavaScript, a cookie can
be created like this:
[Link] = "username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:
[Link] = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs
to the current page.
[Link] = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this: var x = [Link];

[Link] will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript

With JavaScript, you can change a cookie the same way as you create it: [Link] = "username=John
Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
The old cookie is overwritten.

Delete a Cookie with JavaScript

Deleting a cookie is very simple. You don't have to specify a cookie value when you delete a cookie. Just set the
expires parameter to a passed date:
[Link] = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you
delete a cookie if you don't specify the path.

The Cookie String

The [Link] property looks like a normal text string. But it is not. Even if you write a whole cookie
string to [Link], when you read it out again, you can only see the name-value pair of it. If you set a
new cookie, older cookies are not overwritten. The new cookie is added to [Link], so if you read
[Link] again you will get something like: cookie1 = value; cookie2 = value;

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the
cookie value in the cookie string.

JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a visitor. The first time a visitor arrives
to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie. The next time
the visitor arrives at the same page, he/she will get a welcome message. For the example we will create 3
JavaScript functions:

1. A function to set a cookie value


2. A function to get a cookie value
3. A function to check a cookie value

A Function to Set a Cookie

First, we create a function that stores the name of the visitor in a cookie variable:

function setCookie(cname, cvalue, exdays) {


var d = new Date();
[Link]([Link]() + (exdays*24*60*60*1000));
var expires = "expires="+ [Link]();
[Link] = cname + "=" + cvalue + ";" + expires + ";path=/";
}

Example explained: The parameters of the function above are the name of the cookie (cname), the value of
the cookie (cvalue), and the number of days until the cookie should expire (exdays). The function sets a cookie
by adding together the cookiename, the cookie value, and the expires string.

A Function to Get a Cookie

Then, we create a function that returns the value of a specified cookie:

function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent([Link]);
var ca = [Link](';');
for(var i = 0; i <[Link]; i++) {
var c = ca[i];
while ([Link](0) == ' ') {
c = [Link](1);
}
if ([Link](name) == 0) {
return [Link]([Link], [Link]);
}
}
return "";
}

Function explained:

Take the cookiename as parameter (cname).


Create a variable (name) with the text to search for (cname + "=").
Decode the cookie string, to handle cookies with special characters, e.g. '$'
Split [Link] on semicolons into an array called ca (ca = [Link](';')).
Loop through the ca array (i = 0; i < [Link]; i++), and read out each value c = ca[i]).
If the cookie is found ([Link](name) == 0), return the value of the cookie ([Link]([Link], [Link]).

If the cookie is not found, return "".

A Function to Check a Cookie

Last, we create the function that checks if a cookie is set. If the cookie is set it will display a greeting. If the
cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie
for 365 days, by calling the setCookie function:

function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}

All Together Now

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
[Link]([Link]() + (exdays*24*60*60*1000));
var expires = "expires=" + [Link]();
[Link] = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent([Link]);
var ca = [Link](';');
for(var i = 0; i < [Link]; i++) {
var c = ca[i];
while ([Link](0) == ' ') {
c = [Link](1);
}
if ([Link](name) == 0) {
return [Link]([Link], [Link]);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body ></html>

The example above runs the checkCookie() function when the page loads.

JavaScript HTML Input Examples

Examples of using JavaScript to access and manipulate HTML input objects.

Button Object

Disable a button

<form>
<input type="button" id="btn01" value="OK">
</form>
<p>Click the "Disable" button to disable the "OK" button:</p>
<button ><script>
function disableElement() {
[Link]("btn01").disabled = true;
}
</script>

Find the name of a button

<form id="frm1" action="/action_page.php">


<button id="btn1" name="subject" type="submit" value="HTML">HTML</button>
</form>
<p>Click the "Try it" button to display the name of the "HTML" button:</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("btn1").name;
[Link]("demo").innerHTML = x;
}
</script>

Find the type of a button

<button id="btn1" type="button">HTML</button>


<p>Click the "Try it" button to return the type of the "HTML" button:</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("btn1").type;
[Link]("demo").innerHTML = x;
}
</script>

Find the value of a button

<form id="frm1" action="/action_page.php">


<button id="btn1" name="subject" type="submit" value="fav_HTML">HTML</button>
<button id="btn2" name="subject" type="submit" value="fav_CSS">CSS</button>
</form>
<p>Click the "Try it" button to return the value of the "HTML" button:</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("btn1").value;
[Link]("demo").innerHTML = x;
}
</script>

Find the text displayed on a button

<form id="frm1" action="/action_page.php">


<button id="btn1" name="subject" type="submit" value="fav_HTML">HTML</button>
<button id="btn2" name="subject" type="submit" value="fav_CSS">CSS</button>
</form>
<p>Click the "Try it" button to return the text on the "HTML" button:</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("btn1").innerHTML;
[Link]("demo").innerHTML = x;
}
</script>

Find the id of the form a button belongs to

<form id="form1">
<button id="btn1" type="button">HTML</button>
</form>
<p>Click the "Try it" button to display the id of the form the HTML button belongs to:</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("btn1").[Link];
[Link]("demo").innerHTML = x;
}
</script>

Option and Select Objects

Disable and enable a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function disable() {
[Link]("mySelect").disabled=true;
}
function enable() {
[Link]("mySelect").disabled=false;
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<br><br>
<input type="button" value="Disable list">
<input type="button" value="Enable list">
</form>
</body>
</html>

Get the id of the form that contains the dropdown list

<form id="myForm">
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<p>The id of the form is:<p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = [Link]("mySelect").[Link];
</script>

Get the number of options in the dropdown list

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<p>There are <span id="demo">0</span> options in the list.</p>
<script>
[Link]("demo").innerHTML =
[Link]("mySelect").length;
</script>
</body>
</html>

Turn the dropdown list into a multiline list

<!DOCTYPE html>
<html>
<head>
<script>
function changeSize() {
[Link]("mySelect").size = 4;
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Melon</option>
</select>
<input type="button" value="Change size">
</form>
</body>
</html>

Select multiple options in a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function selectMultiple() {
[Link]("mySelect").multiple = true;
}
</script>
</head>
<body>
<form>
<select id="mySelect" size="4">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" value="Select multiple">
</form>
<p>Before you click "Select multiple", you cannot select more than one option (by holding down
the Shift or Ctrl key).</p>
<p>After you have clicked "Select multiple", you can.</p>
</body>
</html>

Display the selected option in a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function getOption() {
var obj = [Link]("mySelect");
[Link]("demo").innerHTML =
[Link][[Link]].text;
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br><br>
<input type="button" value="Click Me!">
</form>
<p id="demo"></p>
</body>
</html>

Display all options from a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function getOptions() {
var x = [Link]("mySelect");
var txt = "";
var i;
for (i = 0; i < [Link]; i++) {
txt = txt + " " + [Link][i].text;
}
[Link]("demo").innerHTML = txt;
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br><br>
<input type="button" value="Output all options">
</form>
<p id="demo"></p>
</body>
</html>

Display the index of the selected option in a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function getIndex() {
[Link]("demo").innerHTML =
[Link]("mySelect").selectedIndex;
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br><br>
<input type="button" >value="Display the index of the selected option">
</form>
<p id="demo"></p>
</body>
</html>

Change the text of the selected option

<!DOCTYPE html>
<html>
<head>
<script>
function changeText() {
x = [Link]("mySelect");
[Link][[Link]].text = "Melon";
}
</script>
</head>
<body>
<form>
Select your favorite fruit:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<br><br>
<input type="button" value="Set text of selected option">
</form>
</body>
</html>

Remove options from a dropdown list

<!DOCTYPE html>
<html>
<head>
<script>
function removeOption() {
var x = [Link]("mySelect");
[Link]([Link]);
}
</script>
</head>
<body>
<form>
<select id="mySelect">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<input type="button" value="Remove the selected option">
</form>
</body>
</html>

JavaScript HTML DOM Events Examples

Examples of using JavaScript to react to events

Input Events

onblur - When a user leaves an input field

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" ><p>When you leave the input field, a function is triggered which transforms the input text to
upper case.</p>
</body>
</html>

onchange - When a user changes the content of an input field

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" ><p>When you leave the input field, a function is triggered which transforms the input text to
upper case.</p>
</body>
</html>

onchange - When a user selects a dropdown value

<!DOCTYPE html>
<html>
<head>
<script>
function preferedBrowser() {
prefer = [Link][0].[Link];
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>
<form>
Choose which browser you prefer:
<select id="browsers" > <option value="Chrome">Chrome</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Firefox">Firefox</option>
</select>
</form>
</body>
</html>

onfocus - When an input field gets


focus

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
[Link] = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" ><p>When the input field gets focus, a function is triggered which changes the background-
color.</p>
</body>
</html>

onselect - When input text is selected

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "You selected some text";
}
</script>
</head>
<body>
Some text: <input type="text" value="Hello world!" ><p id="demo"></p>
</body>
</html>

onsubmit - When a user clicks the submit button

<!DOCTYPE html>
<html>
<head>
<script>
function confirmInput() {
fname = [Link][0].[Link];
alert("Hello " + fname + "! You will now be redirected to [Link]");
}
</script>
</head>
<body>
<form action="[Link]
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>

onreset - When a user clicks the reset button

<!DOCTYPE html>
<html>
<head>
<script>
function message() {
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form > Enter your name: <input type="text" size="20">
<input type="reset">
</form>
</body>
</html>

onkeydown - When a user is pressing/holding down a key

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</head>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" ></body>
</html>

onkeypress - When a user is pressing/holding down a key

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</head>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" ></body>
</html>

onkeyup - When the user releases a key

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
}
</script>
</head>
<body>
<p>A function is triggered when the user releases a key in the input field. The function
transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" ></body>
</html>

onkeyup - When the user releases a key

<!DOCTYPE html>
<html>
<head>
<script>
function writeMessage() {
[Link][0].[Link] = [Link][0].[Link];
}
</script>
</head>
<body>
<p>The onkeyup event occurs when the a keyboard key is on its way UP.</p>
<form>
Enter your name:
<input type="text" name="myInput" size="20">
<input type="text" name="mySecondInput" size="20">
</form>
</body>
</html>

onkeydown vs onkeyup - Both

<!DOCTYPE html>
<html>
<head>
<script>
function color(color) {
[Link][0].[Link] = color;
}
</script>
</head>
<body>
<form>
Write a message:<br>
<input
type="text"
> >name="myInput">
</form>
</body>
</html>

Mouse Events

onmouseover/onmouseout - When the mouse passes over an element

<!DOCTYPE html>
<html>
<body>
<h1 over this text</h1>
</body>
</html>

onmousedown/onmouseup - When pressing/releasing a mouse button

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(elmnt, clr) {
[Link] = clr;
}
</script>
</head>
<body>
<p >Click the text to change the color. A function, with parameters, is triggered when the mouse
button is pressed down, and again, with other parameters, when the mouse button is released.
</p>
</body>
</html>

onmousedown - When mouse is clicked: Alert which element

<!DOCTYPE html>
<html>
<head>
<script>
function whichElement(e) {
var targ;
if (!e) {
var e = [Link];
}
if ([Link]) {
targ=[Link];
} else if ([Link]) {
targ=[Link];
}
var tname;
tname = [Link];
alert("You clicked on a " + tname + " element.");
}
</script>
</head>
<body >

<p>Click somewhere in the document. An alert box will alert the name of the element you
clicked on.</p>
<h3>This is a heading</h3>
<img border="0" src="[Link]" alt="Smiley" width="32" height="32">
<p>This is a paragraph.</p>

</body>
</html>

onmousedown - When mouse is clicked: Alert which button

<!DOCTYPE html>
<html>
<head>
<script>
function WhichButton(event) {
alert("You pressed button: " + [Link])
}
</script>
</head>
<body>

<div this text (with one of your mouse-buttons)


<p>
0 Specifies the left mouse-button<br>
1 Specifies the middle mouse-button<br>
2 Specifies the right mouse-button</p>
<p><strong>Note:</strong> Internet Explorer 8, and earlier, returns another result:<br>
1 Specifies the left mouse-button<br>
4 Specifies the middle mouse-button<br>
2 Specifies the right mouse-button</p>

</div>
</body>
</html>

onmousemove/onmouseout - When moving the mouse pointer over/out of an image

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e) {
x = [Link];
y = [Link];
coor = "Coordinates: (" + x + "," + y + ")";
[Link]("demo").innerHTML = coor
}

function clearCoor() {
[Link]("demo").innerHTML = "";
}
</script>
</head>
<body style="margin:0px;">

<div id="coordiv" style="width:199px;height:99px;border:1px solid"


><p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>

</body>
</html>

onmouseover/onmouseout - When moving the mouse over/out of an image

<!DOCTYPE html>
<html>
<head>
<script>
function bigImg(x) {
[Link] = "64px";
[Link] = "64px";
}
function normalImg(x) {
[Link] = "32px";
[Link] = "32px";
}
</script>
</head>
<body>
<img border="0" src="[Link]"
alt="Smiley" width="32" height="32">
<p>The function bigImg() is triggered when the user moves the mouse pointer over the
image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of the image.</p>
</body>
</html>

onmouseover an image map

<!DOCTYPE html>
<html>
<head>
<script>
function writeText(txt) {
[Link]("desc").innerHTML = txt;
}
</script>
</head>
<body>
<img src ="[Link]" width ="145" height ="126" alt="Planets" usemap="#planetmap" />
<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
Sun and the gas giant planets like Jupiter are by far the largest
objects in our Solar System.')"
href ="[Link]" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"


planet Mercury is very difficult to study from the Earth because
it is always so close to the Sun.')"
href ="[Link]" target ="_blank" alt="Mercury" />

<area shape ="circle" coords ="124,58,8"


the 1960s, Venus was often considered a twin sister to the Earth
because Venus is the nearest planet to us, and because the two planets seem to share many
characteristics.')"
href ="[Link]" target ="_blank" alt="Venus" />
</map>

<p id="desc">Mouse over the sun and the planets and see the different descriptions.</p>
</body>
</html>

Click Events

onclick - When button is clicked

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button me</button>
<p id="demo"></p>
</body>
</html>

ondblclick - When a text is double-clicked

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
</script>
</head>
<body>
<p this paragraph to trigger a function.</p>
<p id="demo"></p>
</body>
</html>

Load Events

onload - When the page has been loaded

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</head>
<body ><h2>Hello World!</h2>
</body>
</html>

onload - When an image has been loaded

<!DOCTYPE html>
<html>
<head>
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="[Link]" width="100" height="132">
</body>
</html>

onerror - When an error occurs when loading an image

<!DOCTYPE html>
<html>
<head>
<script>
function imgError() {
alert('The image could not be loaded.');
}
</script>
</head>
<body>
<img src="[Link]" ><p>A function is triggered if an error occurs when loading the image. The function shows an
alert box with a text.
In this example we refer to an image that does not exist, therefore the onerror event
occurs.</p>
</body>
</html>

onunload - When the browser closes the document

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Thank you for visiting W3Schools!");
}
</script>
</head>
<body ><h2>Welcome to my Home Page</h2>
<p>Close this window or press F5 to reload the page.</p>
</body>
</html>

onresize - When the browser window is resized

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var w = [Link];
var h = [Link];
var txt = "Window size: width=" + w + ", height=" + h;
[Link]("demo").innerHTML = txt;
}
</script>
</head>
<body ><p>Try to resize the browser window.</p>
<p id="demo"> </p>
<p>Note: this example will not work properly in IE8 and earlier. IE8 and earlier do not
support the outerWidth/outerHeight propery of the window object.</p>
</body>
</html>

Others

What is the keycode of the key pressed?

<!DOCTYPE html>
<html>
<head>
<script>
function whichButton(event) {
[Link]("demo").innerHTML = [Link];
}
</script>
</head>
<body ><p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Click on this page, and press a key on your keyboard.</p>
<p id="demo"></p>
</body>
</html>

What are the coordinates of the cursor?

<!DOCTYPE html>
<html>
<head>
<script>
function show_coords(event) {
[Link]("demo").innerHTML = "X= " + [Link] + "<br>Y= " +
[Link]; // E.g. X = 254 Y = 22
}
</script>
</head>
<body>
<p >Click this paragraph to display the x and y coordinates of the mouse pointer.</p>
<p id="demo"></p>
</body>
</html>

What are the coordinates of the cursor, relative to the screen?

<!DOCTYPE html>
<html>
<head>
<script>
function coordinates(event) {
[Link]("demo").innerHTML = "X = " + [Link] + "<br>Y = " +
[Link];
}
</script>
</head>
<body>
<p >Click this paragraph, to display the x and y coordinates of the cursor, relative to the
screen.
</p>
<p id="demo"></p>
</body>
</html>

Was the shift key pressed?

<!DOCTYPE html>
<html>
<head>
<script>
function isKeyPressed(event) {
var text = "The shift key was NOT pressed!";
if ([Link] == 1) {
text = "The shift key was pressed!";
}
[Link]("demo").innerHTML = text;
}
</script>
</head>
<body ><p>Click on this paragraph. An alert box will tell you if you pressed the shift key or
not.</p>
<p id="demo"></p>
</body>
</html>

Which event type occurred?

<!DOCTYPE html>
<html>
<head>
<script>
function getEventType(event) {
[Link]("demo").innerHTML = [Link];
}
</script>
</head>
<body>
<p >Click on this paragraph. A message will tell what type of event was triggered.</p>
<p id="demo"></p>
</body>
</html>

The HTML DOM Attribute Object

The Attr Object

In the HTML DOM, the Attr object represents an HTML attribute.


An HTML attribute always belongs to an HTML element.

The NamedNodeMap Object

In the HTML DOM, the NamedNodeMap object represents an unordered collection of an elements attribute
nodes.
Nodes in a NamedNodeMap can be accessed by name or by index (number).

Properties and Methods

Property / Method Description


[Link] Returns true if the attribute is of type Id, otherwise it returns false
[Link] Returns the name of an attribute
[Link] Sets or returns the value of the attribute
[Link] Returns true if the attribute has been specified, otherwise it returns false
[Link]() Returns a specified attribute node from a NamedNodeMap
[Link]() Returns the attribute node at a specified index in a NamedNodeMap
[Link] Returns the number of attribute nodes in a NamedNodeMap
[Link] Removes a specified attribute node
em()
[Link]() Sets the specified attribute node (by name)

HTML DOM getNamedItem() Method

Get the value of the onclick attribute of a button element:

<p>Click the button to get the value of the onclick attribute of the button element.</p>
<button it</button>
<p><strong>Note:</strong> Internet Explorer 8 and earlier does not support the getNamedItem
method.</p>
<p id="demo"></p>
<script>
function myFunction() {
var a = [Link]("BUTTON")[0];
var x = [Link]("onclick").value;
[Link]("demo").innerHTML = x; // myFunction()
}
</script>

Definition and Usage - The getNamedItem() method returns the attribute node with the specified name from
a NamedNodeMap object.

Syntax: [Link](nodename)

HTML DOM item() Method

Get the name of the first attribute of a <button> element:

var x = [Link]("BUTTON")[0].[Link](0).nodeName;

Definition and Usage - The item() method returns the node at the specified index in a NamedNodeMap, as a
Node object. The nodes are sorted as they appear in the source code, and the index starts at 0.

Note: There are two ways to access an attribute node at the specified index in a NamedNodeMap:
This syntax:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
color: red;
padding: 10px;
width: 150px;
font-size: 15px;
}
</style>
</head>
<body>
<p>Click the button to get the name of the button element's second attribute.</p>
<button class="example">Try it</button>
<p>In this example, the name of the first attribute is "onclick", and the second is
"class".</p>
<p><strong>Note:</strong> In Internet Explorer 8 and earlier, the attributes property will
return a collection of all possible attributes for the element, and will, in this example,
display the name of a different attribute.</p>
<p id="demo"></p>
<script>
function myFunction() {
var a = [Link]("BUTTON")[0];
var x = [Link](1).name;
[Link]("demo").innerHTML = x; // class
}
</script>
</body>
</html>

Will produce the same result as this syntax: [Link]("BUTTON")[0].attributes[1]; //


The 2nd attribute

You can use whatever method you like, however, the most common method is [index].
Tip: Use the length property to return the number of nodes in a NamedNodeMap object

Syntax
[Link](index)
or simply:
namednodemap[index]

HTML DOM length Property

Get the number of attributes of a <button> element:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
color: red;
padding: 5px;
width: 150px;
font-size: 15px;
}
</style>
</head>
<body>
<p>Click the button to see how many attributes the button element has:</p>
<button class="example">Try it</button>
<p><strong>Note:</strong> In Internet Explorer 8 and earlier, the attributes property will
return a collection of all possible attributes for the element, and will, in this example,
display a much higher number than 1.</p>
<p>The result should be 2 (the button element's onclick and class attribute).</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("BUTTON")[0].[Link];
[Link]("demo").innerHTML = x; // 2
}
</script>
</body>
</html>

Definition and Usage - The length property returns the number of nodes in a NamedNodeMap object. A Node
object's attributes is an example of a NamedNodeMap object. This property is read-only.
Tip: Use the item() method to return a node at the specified index in a NamedNodeMap object.

Note: In Internet Explorer 8 and earlier, the length property for attributes will return the number of all
possible attributes for an element.

Syntax: [Link]

More Example
Loop through all attributes of a <button> element and output the name of each attribute:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
color: red;
padding: 5px;
width: 150px;
font-size: 15px;
}
</style>
</head>
<body>
<p>Click the button to get all attribute names of the button element.</p>
<button id="myBtn" class="example">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
var x = [Link]("myBtn").attributes;
var i;
for (i = 0; i < [Link]; i++) {
txt += "Attribute name: " + x[i].name + "<br>";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>

HTML DOM name Property

Get the name of an attribute:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the name of the button's first attribute.</p>
<button it</button>
<p><strong>Note:</strong> In Internet Explorer 8 and earlier, the attributes property will
return a collection of all possible attributes for the element, and will, in this example,
display the name of a different attribute.</p>
<p id="demo"></p>
<script>
function myFunction() {
var btn = [Link]("BUTTON")[0];
var x = [Link][0].name;
[Link]("demo").innerHTML = x; // onclick
}
</script>
</body>
</html>

Definition and Usage - The name property returns the name of the attribute. This property is read-only.

Tip: You can use the [Link] property to get the value of an attribute.

Syntax: [Link]

HTML DOM removeNamedItem() Method

Remove the type attribute from an input button:

<!DOCTYPE html>
<html>
<body>
<input type="button" value="OK">
<p>Click the button below to remove the type attribute of the input element above.</p>
<button it</button>
<p><strong>Note:</strong> When removing the type attribute of an input element, the element
will be of type <em>text</em>, which is the default value.</p>
<p><strong>Note:</strong> In Internet Explorer 8 and earlier, the removedNamedItem returns the
attribute as it should, but it does not remove the attribute.</p>
<script>
function myFunction() {
var btn = [Link]("INPUT")[0];
[Link]("type");
}
</script>
</body>
</html>

Definition and Usage - The removeNamedItem() method removes the node with the specified name in a
NamedNodeMap object.

Syntax: [Link](nodename)

HTML DOM setNamedItem() Method

Set a H1's class attribute:

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to set the H1's class attribute to "democlass".</p>
<button it</button>
<script>
function myFunction() {
var h = [Link]("H1")[0];
var typ = [Link]("class");
[Link] = "democlass";
[Link](typ);
}
</script>
</body>
</html>

Definition and Usage - The setNamedItem() method adds the specified node to the NamedNodeMap. If the
node already exists, it will be replaced, and the replaced node will be the return value, otherwise the return
value will be null.

Tip: Instead of working with attribute nodes, you could use the [Link]() method to add an
attribute with a value to an element.
Syntax: [Link](node)

HTML DOM specified Property

Find out if an attribute has been specified or not:

<p>Click the button find out if the button has an onclick attribute specified.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var btn = [Link]("BUTTON")[0];
var x = [Link]("onclick").specified;
[Link]("demo").innerHTML = x; // true
}
</script>

Definition and Usage - The specified property returns true if the attribute is specified. Returns true also if the
attribute has been created but not been attached to an element yet. Otherwise it returns false.

HTML DOM value Property

Get the value of the <button> element's first attribute:

<p>Click the button to display the value of the button's first attribute value.</p>
<button it</button>
<p><strong>Note:</strong> In Internet Explorer 8 and earlier, the attributes property will
return a collection of all possible attributes for the element, and will, in this example,
display the name of a different attribute.</p>
<p id="demo"></p>
<script>
function myFunction() {
var btn = [Link]("BUTTON")[0];
var x = [Link][0].value;
[Link]("demo").innerHTML = x; // myFunction()
}
</script>

Definition and Usage - The value property sets or returns the value of the attribute.

The Console Object

Console Object - The Console object provides access to the browser's debugging console.

Method Description
assert() Writes an error message to the console if the assertion is false
clear() Clears the console
count() Logs the number of times that this particular call to count() has been called
error() Outputs an error message to the console
group() Creates a new inline group in the console. This indents following console
messages by an additional level, until [Link]() is called
groupCollapsed() Creates a new inline group in the console. However, the new group is created
collapsed. The user will need to use the disclosure button to expand it
groupEnd() Exits the current inline group in the console
info() Outputs an informational message to the console
log() Outputs a message to the console
table() Displays tabular data as a table
time() Starts a timer (can track how long an operation takes)
timeEnd() Stops a timer that was previously started by [Link]()
trace() Outputs a stack trace to the console
warn() Outputs a warning message to the console

HTML DOM [Link]() Method

Write a message to the console, only if the first argument is false:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript [Link]() Method</h1>
<p>Press F12 on your keyboard to view the message in the console view.</p>
<script>
[Link]([Link]("demo"), "You have no element with ID 'demo'");
</script>
</body>
</html>

Definition and Usage - The [Link]() method writes a message to the console, but only if an expression
evaluates to false.

HTML DOM [Link]() Method

Clear all messages in the console:

<h1>JavaScript [Link]() Method</h1>


<p>Press F12 on your keyboard to view the message in the console view.</p>
<p>Click the button to clear the console:</p>
<button Console</button>
<script>
[Link]("Hello! Press the button to clear the console!");
function myFunction() {
[Link]();
}
</script>

Definition and Usage - The [Link]() method clears the console. The [Link]() method will also
write a message in the console: "Console was cleared".

HTML DOM [Link]() Method

Write to the console the number of time the [Link]() is called inside the loop:

<h1>JavaScript [Link]() Method</h1>


<p>Press F12 on your keyboard to view the message in the console view.</p>
<script>
for (i = 0; i < 10; i++) {
[Link]();
}
</script>

Definition and Usage - Writes to the console the number of times that particular [Link]() is called. You
can add a label that will be included in the console view. By default the label "default" will be added.

HTML DOM [Link]() Method

Write an error to the console: [Link]("You made a mistake");


Definition and Usage - The [Link]() method writes an error message to the console. The console is
useful for testing purposes.

HTML DOM [Link]() Method

Create a group of messages in the console:

[Link]("Hello world!");
[Link]();
[Link]("Hello again, this time inside a group!");

Definition and Usage - The [Link]() method indicates the start of a message group. All messages will
from now on be written inside this group.

Tip: Use the [Link]() method to end the group.

Tip: Use the [Link]() method to hide the message group (collapsed by default).

HTML DOM [Link]() Method

Write a message to the console: [Link]("Hello world!")


Definition and Usage - The [Link]() method writes a message to the console.

Tip: When testing the console methods, be sure to have the console view visible (press F12 to view the
console).

More Examples

Using an object as the message:

var myObj = { firstname : "John", lastname : "Doe" };


[Link](myObj);

Using an array as the message:

var myArr = ["Orange", "Banana", "Mango", "Kiwi" ];


[Link](myObj);

HTML DOM [Link]() Method

Write to the console: [Link]("Hello world!");

Definition and Usage - The [Link]() method writes a message to the console. The console is useful for
testing purposes.

HTML DOM [Link]() Method

Write a table in the console: [Link](["Audi", "Volvo", "Ford"])

Definition and Usage - The [Link]() method writes a table in the console view. The first parameter is
required, and must be either an object, or an array, containing data to fill the table.

HTML DOM [Link]() Method


How long does it take to perform a for-loop 100.000 times:

[Link]();
for (i = 0; i < 100000; i++) {
// some code
}
[Link]();

Definition and Usage - The [Link]() method starts a timer in the console view. This method allows you
to time certain operations in your code for testing purposes.

Use the [Link]() method to end the timer and display the result in the [Link]. Use
the label parameter to name the timer, then you are able to have many timers on the same page.

HTML DOM [Link]() Method

Show the trace of how the code ended up here:

function myFunction() {
myOtherFunction();
}
function myOtherFunction() {
[Link]();
}

Definition and Usage - The [Link]() method displays a trace that show how the code ended up at a
certain point.

HTML DOM [Link]() Method

Write a warning to the console: [Link]("This is a warning!");

Definition and Usage - The [Link]() method writes a warning to the console.

The HTML DOM Document Object

The Document Object - When an HTML document is loaded into a web browser, it becomes a document
object. The document object is the root node of the HTML document.

Document Object Properties and Methods


The following properties and methods can be used on HTML documents:

Property / Method Description


activeElement Returns the currently focused element in the document
addEventListener() Attaches an event handler to the document
adoptNode() Adopts a node from another document
anchors Returns a collection of all <a> elements in the document that have a
name attribute
applets Returns a collection of all <applet> elements in the document
baseURI Returns the absolute base URI of a document
body Sets or returns the document's body (the <body> element)
close() Closes the output stream previously opened with [Link]()
cookie Returns all name/value pairs of cookies in the document
charset Deprecated. Use characterSet instead. Returns the character encoding
for the document
characterSet Returns the character encoding for the document
createAttribute() Creates an attribute node
createComment() Creates a Comment node with the specified text
createDocumentFragment() Creates an empty DocumentFragment node
createElement() Creates an Element node
createEvent() Creates a new event
createTextNode() Creates a Text node
defaultView Returns the window object associated with a document, or null if none is
available.
designMode Controls whether the entire document should be editable or not.
doctype Returns the Document Type Declaration associated with the document
documentElement Returns the Document Element of the document (the <html> element)
documentMode Returns the mode used by the browser to render the document
documentURI Sets or returns the location of the document
domain Returns the domain name of the server that loaded the document
domConfig Obsolete. Returns the DOM configuration of the document
embeds Returns a collection of all <embed> elements the document
execCommand() Invokes the specified clipboard operation on the element currently
having focus.
forms Returns a collection of all <form> elements in the document
fullscreenElement Returns the current element that is displayed in fullscreen mode
fullscreenEnabled() Returns a Boolean value indicating whether the document can be
viewed in fullscreen mode
getElementById() Returns the element that has the ID attribute with the specified value
getElementsByClassName() Returns a HTMLCollection containing all elements with the specified
class name
getElementsByName() Returns a HTMLCollection containing all elements with a specified name
getElementsByTagName() Returns a HTMLCollection containing all elements with the specified tag
name
hasFocus() Returns a Boolean value indicating whether the document has focus
head Returns the <head> element of the document
images Returns a collection of all <img> elements in the document
implementation Returns the DOMImplementation object that handles this document
importNode() Imports a node from another document
inputEncoding Returns the encoding, character set, used for the document
lastModified Returns the date and time the document was last modified
links Returns a collection of all <a> and <area> elements in the document
that have a href attribute
normalize() Removes empty Text nodes, and joins adjacent nodes
normalizeDocument() Removes empty Text nodes, and joins adjacent nodes
open() Opens an HTML output stream to collect output from [Link]()
querySelector() Returns the first element that matches a specified CSS selector(s) in the
document
querySelectorAll() Returns a static NodeList containing all elements that matches a
specified CSS selector(s) in the document
readyState Returns the (loading) status of the document
referrer Returns the URL of the document that loaded the current document
removeEventListener() Removes an event handler from the document (that has been attached
with the addEventListener() method)
renameNode() Renames the specified node
scripts Returns a collection of <script> elements in the document
strictErrorChecking Sets or returns whether error-checking is enforced or not
title Sets or returns the title of the document
URL Returns the full URL of the HTML document
write() Writes HTML expressions or JavaScript code to a document
writeln() Same as write(), but adds a newline character after each statement

HTML DOM activeElement Property

Get the currently focused element in the document:


<!DOCTYPE html>
<html>
<body ><p>Click anywhere in the document to display the active element.</p>
<input type="text" value="An input field">
<button>A Button</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link];
[Link]("demo").innerHTML =
x;
}
</script>
</body>
</html>

Definition and Usage - The activeElement property returns the currently focused element in the document.

HTML DOM addEventListener() Method

Attach a click event to the document. When the user clicks anywhere in the document, output "Hello World" in a
<p> element with id="demo":

<p>This example uses the addEventListener() method to attach a click event to the
document.</p>
<p>Click anywhere in the document.</p>
<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer
8 and earlier versions.</p>
<p id="demo"></p>
<script>
[Link]("click", function(){
[Link]("demo").innerHTML = "Hello World!"; // Hellow World!
});
</script>

Definition and Usage - The [Link]() method attaches an event handler to the document.

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions, and Opera
6.0 and earlier versions. However, for these specific browser versions, you can use the attachEvent() method
to attach event handlers.

Syntax: [Link](event, function, useCapture)

Paramet Description
er
event Required. A String that specifies the name of the event. Note: Do not use the "on" prefix. For
example, use "click" instead of "onclick".
function Required. Specifies the function to run when the event occurs.
When the event occurs, an event object is passed to the function as the first parameter. The type
of the event object depends on the specified event. For example, the "click" event belongs to the
MouseEvent object.
useCaptu Optional. A Boolean value that specifies whether the event should be executed in the capturing
re or in the bubbling phase.
Possible values:
 true - The event handler is executed in the capturing phase
 false- Default. The event handler is executed in the bubbling phase

HTML DOM body Property


Change the background color of the current document:

<p>Click the button to change the background color of the document.</p>


<button it</button>
<script>
function myFunction() {
[Link] = "yellow";
}
</script>

Definition and Usage - The body property sets or returns the document's body.

On return, this property returns the <body> element of the current document. On set, this property
overwrites all child elements inside the existing <body> element, and replaces it with the new, specified
content.

Tip: The difference between this property and the [Link] property, is that the
[Link] element returns the <body> element, while the [Link] returns the
<html> element.

Syntax
Return the body property: [Link]

Set the body property: [Link] = newContent

More Examples

Get the HTML content of the current document:

<p>Click the button to display the HTML content


of the document.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link];
[Link]("demo").innerHTML = x;
}
</script>

Change the HTML content of the current document (will overwrite all existing HTML elements inside
<body>):

<p>Click the button to change the HTML content of the document.</p>


<button it</button>
<script>
function myFunction() {
[Link] = "Some new HTML content";
}
</script>

Create a <p> element with some text and append it to the document's body:

<p>Click the button to create a P element with some text, and append it to the document's
body.</p>
<button it</button>
<script>
function myFunction() {
var x = [Link]("P");
var t = [Link]("This is a paragraph.");
[Link](t);
[Link](x);
}
</script>

HTML DOM createAttribute() Method

Create a class attribute, with the value "democlass", and insert it to an <h1>
element:

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to
the H1 element above.</p>
<button it</button>
<script>
function myFunction() {
var h1 = [Link]("H1")[0];
var att = [Link]("class");
[Link] = "democlass";
[Link](att);
}
</script>
</body>
</html>

Definition and Usage - The createAttribute() method creates an attribute with the specified name, and returns
the attribute as an Attr object.

HTML DOM createComment() Method

Create a comment node, and insert it to the HTML document:

<p>Click the button to create, and add, a comment to the HTML document.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = [Link]("My personal comments");
[Link](c);
var x = [Link]("demo");
[Link] = "A comment was added to this document, but as you know, comments are
invisible.";
}
</script>

Definition and Usage - The createComment() method creates a Comment node with the specified text.
HTML DOM createElement() Method

Create a <button> element:

<p>Click the button to make a BUTTON element.</p>


<button it</button>
<script>
function myFunction() {
var btn = [Link]("BUTTON");
[Link](btn);
}
</script>
</body>
</html>

HTML elements often contains text. To create a button with text, use the innerText or innerHTML properties of
the element object:

Create a button with text:

<p>Click the button to make a BUTTON element with text.</p>


<button it</button>
<script>
function myFunction() {
var btn = [Link]("BUTTON");
[Link] = "CLICK ME";
[Link](btn);
}
</script>

Definition and Usage - The createElement() method creates an Element Node with the specified name.

More Examples

Create a <p> element with some text, use innerText to set the text, and append it to the
document:

<p>Click the button to create a P element with some text.</p>


<button it</button>
<script>
function myFunction() {
var para = [Link]("P");
[Link] = "This is a paragraph.";
[Link](para);
}
</script>

Create a <p> element and append it to a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to create a P element with some text, and append it to DIV.</p>
<div id="myDIV">
A DIV element
</div>
<button it</button>
<script>
function myFunction() {
var para = [Link]("P");
[Link] = "This is a paragraph.";
[Link]("myDIV").appendChild(para);
}
</script>
</body>
</html>

createEvent() Event Method

Simulate a mouseover event:

<!DOCTYPE html>
<html>
<body>
<style>
div {
padding:50px;
background-color: Tomato;
color: white;
}
</style>
<script>
function myFunction(event) {
var x = [Link]("MouseEvent");
[Link]("mouseover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false,
0, null);

[Link]("myDiv").dispatchEvent(x);
}
</script>
<h1>The createEvent() Method</h1>
<p>The createEvent() method allows you to simulate any event.</p>
<p>In this example, the red div will get a new star every time you mouse over it:</p>
<div += '*';" id="myDiv">*</div>
<br>
<button Mouse Over</button>
</body>
</html>

Definition and Usage - The createEvent() method creates an event object. The event can be of any legal
event type, and must be initialized before use.

Parameter Description
type Required. A String that specifies the type of the event.
Possible values:
AnimationEvent
ClipboardEvent
DragEvent
FocusEvent
HashChangeEvent
InputEvent
KeyboardEvent
MouseEvent
PageTransitionEvent
PopStateEvent
ProgressEvent
StorageEvent
TouchEvent
TransitionEvent
UiEvent
WheelEvent

HTML DOM createTextNode() Method

Create a text node:

<p>Click the button to create a Text Node.</p>


<button it</button>
<script>
function myFunction() {
var t = [Link]("Hello World");
[Link](t);
}
</script>

HTML elements often consists of both an element node and a text node.

To create a header (e.g. <h1>), you must create both an <h1> element and a text node:

Create a <h1> element with some text:

var h = [Link]("H1") // Create a <h1> element


var t = [Link]("Hello World"); // Create a text node
[Link](t); // Append the text to <h1>

Definition and Usage - The createTextNode() method creates a Text Node with the specified text.

HTML DOM forms Collection

Find out how many <form> elements there are in the document:

<form>
First Name: <input type="text" name="fname" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
</form>
<p>Click the button to display the number of form elements in the document.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link];
[Link]("demo").innerHTML = x; // 1
}
</script>

Definition and Usage - The forms collection returns a collection of all <form> elements in the document.

Note: The elements in the collection are sorted as they appear in the source code.

HTML DOM getElementsByName() Method

Get all elements with the specified name:

First Name: <input name="fname" type="text" value="Michael"><br>


First Name: <input name="fname" type="text" value="Doug">
<p>Click the button to get the tag name of the first element in the document that has a name
attribute with the value "fname".</p>
<button it</button>
<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]("fname")[0].tagName;
[Link]("demo").innerHTML = x; // INPUT
}
</script>

Definition and Usage - The getElementsByName() method returns a collection of all elements in the
document with the specified name (the value of the name attribute), as an HTMLCollection object.
The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The
index starts at 0.

HTML DOM hasFocus() Method

Output some text if the document has focus:

<p>Click anywhere in the document (the right frame) to get focus. If you click outside the
document, it will lose focus.</p>
<p id="demo"></p>
<script>
setInterval("myFunction()", 1);

function myFunction() {
var x = [Link]("demo");
if ([Link]()) {
[Link] = "The document has focus.";
} else {
[Link] = "The document DOES NOT have focus.";
}
}
</script>

Definition and Usage - The hasFocus() method returns a Boolean value indicating whether the document (or
any element inside the document) has focus.

HTML DOM images Collection

Find out how many <img> elements there are in the document:

var x = [Link]; // The result of x will be: 3


HTML DOM lastModified Property

Get the date and time the current document was last modified:

<p>Click the button to display the


date and time this document was last
modified.</p>
<button >it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link];
[Link]("demo").innerHTML = x;
}
</script>

Definition and Usage - The lastModified property returns the date and time the current document was last
modified.

HTML DOM links Collection

Find out how many links there are in the document:

var x = [Link]; // The result of x will be: 5

HTML DOM removeEventListener() Method

Remove a "mousemove" event that has been attached with the addEventListener() method:

<p>This document has an onmousemove event handler that displays a random number every time you
move your mouse in this document.</p>
<p>Click the button to remove the event handler.</p>
<button it</button>
<p><strong>Note:</strong> The addEventListener() and removeEventListener() methods are not
supported in Internet Explorer 8 and earlier versions.</p>
<p id="demo"></p>

<script>
[Link]("mousemove", myFunction);
function myFunction() {
[Link]("demo").innerHTML = [Link]();
}
function removeHandler() {
[Link]("mousemove", myFunction);
}
</script>
Definition and Usage - The [Link]() method removes an event handler that has
been attached with the [Link]() method.

Note: To remove event handlers, the function specified with the addEventListener() method must be an
external, "named" function, like in the example above (myFunction).

Anonymous functions, like "[Link]("event", function(){ myScript });" will not work.

Note: The removeEventListener() method is not supported in Internet Explorer 8 and earlier versions, and
Opera 6.0 and earlier versions. However, for these specific browser versions, you can use
the detachEvent() method to remove event handlers that have been attached with the attachEvent() method
(see "More Examples" below for a cross-browser solution).

Syntax: [Link](event, function, useCapture)

Parameter Description
Required. A String that specifies the name of the event to remove. Note: Do not use the
"on" prefix.
event
For example, use "click" instead of "onclick".

Required. Specifies the function to remove.


function

Optional. A Boolean value that specifies the event phase to remove the event handler from.
Possible values:
useCapture
 true - Removes the event handler from the capturing phase
 false- Default. Removes the event handler from the bubbling phase
Note: If the event handler was attached two times, one with capturing and one bubbling,
each must be removed separately.

HTML DOM scripts Collection

Find out how many <script> elements there are in the document: var x = [Link];
// The result of x will be: 2

HTML DOM title Property

Get the title of the current document: var x = [Link];

HTML DOM URL Property

Get the full URL of the current HTML document: var x = [Link];

Definition and Usage - The URL property returns the full URL of the current HTML document. Note: This
property is similar to the [Link] property.

HTML DOM write() Method

Write some text directly to the HTML document: [Link]("Hello World!");

Definition and Usage - The write() method writes HTML expressions or JavaScript code to a document. The
write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all
existing HTML.

The HTML DOM Element Object


The Element Object - In the HTML DOM, the Element object represents an HTML element, like P, DIV, A,
TABLE, or any other HTML element.

Properties and Methods


The following properties and methods can be used on all HTML elements:

Property / Method Description


accessKey Sets or returns the accesskey attribute of an element
addEventListener() Attaches an event handler to the specified element
appendChild() Adds a new child node, to an element, as the last child node
attributes Returns a NamedNodeMap of an element's attributes
blur() Removes focus from an element
childElementCount Returns the number of child elements an element has
childNodes Returns a collection of an element's child nodes (including text and
comment nodes)
children Returns a collection of an element's child element (excluding text and
comment nodes)
classList Returns the class name(s) of an element
className Sets or returns the value of the class attribute of an element
click() Simulates a mouse-click on an element
clientHeight Returns the height of an element, including padding
clientLeft Returns the width of the left border of an element
clientTop Returns the width of the top border of an element
clientWidth Returns the width of an element, including padding
cloneNode() Clones an element
compareDocumentPosition() Compares the document position of two elements
contains() Returns true if a node is a descendant of a node, otherwise false
contentEditable Sets or returns whether the content of an element is editable or not
dir Sets or returns the value of the dir attribute of an element
exitFullscreen() Cancels an element in fullscreen mode
firstChild Returns the first child node of an element
firstElementChild Returns the first child element of an element
focus() Gives focus to an element
getAttribute() Returns the specified attribute value of an element node
getAttributeNode() Returns the specified attribute node
getBoundingClientRect() Returns the size of an element and its position relative to the viewport
getElementsByClassName() Returns a collection of all child elements with the specified class name
getElementsByTagName() Returns a collection of all child elements with the specified tag name
hasAttribute() Returns true if an element has the specified attribute, otherwise false
hasAttributes() Returns true if an element has any attributes, otherwise false
hasChildNodes() Returns true if an element has any child nodes, otherwise false
id Sets or returns the value of the id attribute of an element
innerHTML Sets or returns the content of an element
innerText Sets or returns the text content of a node and its descendants
insertAdjacentElement() Inserts a HTML element at the specified position relative to the current
element
insertAdjacentHTML() Inserts a HTML formatted text at the specified position relative to the
current element
insertAdjacentText() Inserts text into the specified position relative to the current element
insertBefore() Inserts a new child node before a specified, existing, child node
isContentEditable Returns true if the content of an element is editable, otherwise false
isDefaultNamespace() Returns true if a specified namespaceURI is the default, otherwise
false
isEqualNode() Checks if two elements are equal
isSameNode() Checks if two elements are the same node
isSupported() Returns true if a specified feature is supported on the element
lang Sets or returns the value of the lang attribute of an element
lastChild Returns the last child node of an element
lastElementChild Returns the last child element of an element
namespaceURI Returns the namespace URI of an element
nextSibling Returns the next node at the same node tree level
nextElementSibling Returns the next element at the same node tree level
nodeName Returns the name of a node
nodeType Returns the node type of a node
nodeValue Sets or returns the value of a node
normalize() Joins adjacent text nodes and removes empty text nodes in an
element
offsetHeight Returns the height of an element, including padding, border and
scrollbar
offsetWidth Returns the width of an element, including padding, border and
scrollbar
offsetLeft Returns the horizontal offset position of an element
offsetParent Returns the offset container of an element
offsetTop Returns the vertical offset position of an element
outerHTML Sets or returns the content of an element (including the start tag and
the end tag)
outerText Sets or returns the outer text content of a node and its descendants
ownerDocument Returns the root element (document object) for an element
parentNode Returns the parent node of an element
parentElement Returns the parent element node of an element
previousSibling Returns the previous node at the same node tree level
previousElementSibling Returns the previous element at the same node tree level
querySelector() Returns the first child element that matches a specified CSS
selector(s) of an element
querySelectorAll() Returns all child elements that matches a specified CSS selector(s) of
an element
remove() Removes the element from the DOM
removeAttribute() Removes a specified attribute from an element
removeAttributeNode() Removes a specified attribute node, and returns the removed node
removeChild() Removes a child node from an element
removeEventListener() Removes an event handler that has been attached with the
addEventListener() method
replaceChild() Replaces a child node in an element
requestFullscreen() Shows an element in fullscreen mode
scrollHeight Returns the entire height of an element, including padding
scrollIntoView() Scrolls the specified element into the visible area of the browser
window
scrollLeft Sets or returns the number of pixels an element's content is scrolled
horizontally
scrollTop Sets or returns the number of pixels an element's content is scrolled
vertically
scrollWidth Returns the entire width of an element, including padding
setAttribute() Sets or changes the specified attribute, to the specified value
setAttributeNode() Sets or changes the specified attribute node
style Sets or returns the value of the style attribute of an element
tabIndex Sets or returns the value of the tabindex attribute of an element
tagName Returns the tag name of an element
textContent Sets or returns the textual content of a node and its descendants
title Sets or returns the value of the title attribute of an element
toString() Converts an element to a string

HTML DOM appendChild() Method

Append an item in a list:

<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>Click the button to append an item to the end of the list.</p>
<button it</button>
<script>
function myFunction() {
var node = [Link]("LI");
var textnode = [Link]("Water");
[Link](textnode);
[Link]("myList").appendChild(node);
}
</script>
<p><strong>Note:</strong><br>First create an LI node,<br> then create a Text node,<br> then
append the Text node to the LI node.<br>Finally append the LI node to the list.</p>

Before appending:
 Coffee
 Tea
After appending:
 Coffee
 Tea

 Water

Definition and Usage - The appendChild() method appends a node as the last child of a node.

Tip: If you want to create a new paragraph, with text, remember to create the text as a Text node which you
append to the paragraph, then append the paragraph to the document.

You can also use this method to move an element from one element to another (See "More Examples").

Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.

Move a list item from one list to another:

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>
<p>Click the button to move an item from one list to another.</p>
<button it</button>
<script>
function myFunction() {
var node = [Link]("myList2").lastChild;
[Link]("myList1").appendChild(node);
}
</script>

Before appending:
 Coffee
 Tea
 Water
 Milk
After appending:
 Coffee
 Tea
 Milk

 Water

HTML DOM childElementCount Property

Find out how many child elements a <div> element has:


<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<p>Click the button to find out how many children the div element below has.</p>
<button it</button>

<div id="myDIV">
<p>First p element</p>
<p>Second p element</p>
</div>

<p><strong>Note:</strong> The childElementCount property is not supported in IE8 and earlier


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

<script>
function myFunction() {
var c = [Link]("myDIV").childElementCount;
[Link]("demo").innerHTML = c;
}
</script>
</body>
</html>

Definition and Usage - The childElementCount property returns the number of child elements an element has.

Note: The returned value contains the number of child element nodes, not the number of all child nodes (like
text and comment nodes).

This property is read-only.

Tip: Use the children property to return any child element of a specified element.

Tip: The childElementCount property will produce the same result as [Link].

HTML DOM childNodes Property

Get a collection of the <body> element's child nodes:

<!DOCTYPE html>
<html>
<body><!-- This is a comment node! -->
<p>Click the button get info about the body element's child nodes.</p>
<button it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text
is considered as nodes. Comments are also considered as nodes.</p>
<p id="demo"></p>

<script>
function myFunction() {
var c = [Link];
var txt = "";
var i;
for (i = 0; i < [Link]; i++) {
txt = txt + c[i].nodeName + "<br>";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>

Definition and Usage - The childNodes property returns a collection of a node's child nodes, as a NodeList
object.
The nodes in the collection are sorted as they appear in the source code and can be accessed by index
numbers. The index starts at 0.

Note: Whitespace inside elements is considered as text, and text is considered as nodes. Comments are also
considered as nodes.

Tip: You can use the length property of the NodeList object to determine the number of child nodes, then you
can loop through all child nodes and extract the info you want.
This property is read-only.
Tip: To return a collection of a node's element nodes (excluding text and comment nodes), use
the children property.

Tip: [Link][0] will produce the same result as the firstChild property.

HTML DOM children Property

Get a collection of the <body> element's children:

<p>Click the button to get the tag names of the body element's children.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = [Link];
var txt = "";
var i;
for (i = 0; i < [Link]; i++) {
txt = txt + c[i].tagName + "<br>";
}
[Link]("demo").innerHTML = txt;
}
</script>

Definition and Usage - The children property returns a collection of an element's child elements, as an
HTMLCollection object. The elements in the collection are sorted as they appear in the source code and can be
accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the HTMLCollection object to determine the number of child elements,
then you can loop through all children and extract the info you want.

The difference between this property and childNodes, is that childNodes contain all nodes, including text nodes
and comment nodes, while children only contain element nodes.

More Examples

Find out how many children a <div> element has:

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid
black;
margin: 5px;
}
</style>
</head>
<body>
<p>Click the button to find out how many children the div element below has.</p>
<button it</button>
<div id="myDIV">
<p>First p element (index 0)</p>
<p>Second p element (index 1)</p>
</div>
<p id="demo"></p>

<script>
function myFunction() {
var c = [Link]("myDIV").[Link];
[Link]("demo").innerHTML = c;
}
</script>
</body>
</html>

Change the background color of the second child element of a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<p>Click the button to add a background color to the second child element (index 1) of
div.</p>
<button it</button>
<div id="myDIV">
<p>First p element</p>
<p>Second p element</p>
</div>
<script>
function myFunction() {
var c = [Link]("myDIV").children;
c[1].[Link] = "yellow";
}
</script>
</body>
</html>

Get the text of the third child element (index 2) of a <select> element:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the text of the third child element (index 2) of the select
element.</p>
<select id="mySelect" size="4">
<option>Audi</option>
<option>BMW</option>
<option>Saab</option>
<option>Volvo</option>
</select>
<br><br>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var c = [Link]("mySelect").children;
[Link]("demo").innerHTML = c[2].text;
}
</script>
</body>
</html>

HTML DOM classList Property

Add the "mystyle" class to a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<p>Click the button to add the "mystyle" class to DIV.</p>
<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>
<div id="myDIV">
I am a DIV element
</div>
<script>
function myFunction() {
[Link]("myDIV").[Link]("mystyle");
}
</script>
</body>
</html>

Definition and Usage - The classList property returns the class name(s) of an element, as a DOMTokenList
object. This property is useful to add, remove and toggle CSS classes on an element. The classList property is
read-only, however, you can modify it by using the add() and remove() methods.

Property Description
length Returns the number of classes in the list. This property is read-only

Method Description
add(class1, class2, ...) Adds one or more class names to an element. If the specified class already exist,
the class will not be added
contains(class) Returns a Boolean value, indicating whether an element has the specified class
name.
Possible values:
 true - the element contains the specified class name
 false - the element does not contain the specified class name
item(index) Returns the class name with a specified index number from an element. Index
starts at 0. Returns null if the index is out of range
remove(class1, Removes one or more class names from an element. Note: Removing a class
class2, ...) that does not exist, does NOT throw an error
toggle(class, true|false) Toggles between a class name for an element. The first parameter removes the
specified class from an element, and returns false. If the class does not exist, it is
added to the element, and the return value is true.

The optional second parameter is a Boolean value that forces the class to be
added or removed, regardless of whether or not it already existed. For example:

Remove a class: [Link]("classToRemove", false);


Add a class: [Link]("classToAdd", true);

Note: The second parameter is not supported in Internet Explorer or Opera 12


and earlier.

Add multiple classes to a <div> element:


<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 500px;
height: 50px;
padding: 15px;
border: 1px solid black;
}
.anotherClass {
background-color: coral;
color: white;
}
.thirdClass {
text-transform: uppercase;
text-align: center;
font-size: 25px;
}
</style>
</head>
<body>
<p>Click the button to add multiple classes to DIV.</p>
<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>
<div id="myDIV">
I am a DIV element
</div>
<script>
function myFunction() {
[Link]("myDIV").[Link]("mystyle", "anotherClass", "thirdClass");
}
</script>
</body>
</html>

Remove a class from a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<p>Click the button to remove the "mystyle" class from DIV.</p>
<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<script>
function myFunction() {
[Link]("myDIV").[Link]("mystyle");
}
</script>
</body>
</html>

Remove multiple classes from a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 500px;
height: 50px;
padding: 15px;
border: 1px solid black;
}

.anotherClass {
background-color: coral;
color: white;
}

.thirdClass {
text-transform: uppercase;
text-align: center;
font-size: 25px;
}
</style>
</head>
<body>
<p>Click the button to remove multiple classes from DIV.</p>
<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>
<div id="myDIV" class="mystyle anotherClass thirdClass">
I am a DIV element
</div>
<script>
function myFunction() {
[Link]("myDIV").[Link]("mystyle", "anotherClass", "thirdClass");
}
</script>
</body>
</html>
Toggle between two classes for a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}

.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
</style>
</head>
<body>

<p>Click the button to toggle between two classes.</p>


<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>
<script>
function myFunction() {
[Link]("myDIV").[Link]("newClassName");
}
</script>
</body>
</html>
Get the class name(s) of a <div> element:

<div id="myDIV" class="mystyle anotherClass thirdClass">I am a DIV element</div>


var x = [Link]("myDIV").classList; // Result: mystyle anotherClass thirdClass

Find out how many class names a <div> element has:

var x = [Link]("myDIV").[Link]; // Result: 3

Get the first class name (index 0) of a <div> element:

var x = [Link]("myDIV").[Link](0); // Result: mystyle

Find out if an element has a "mystyle" class:

var x = [Link]("myDIV").[Link]("mystyle"); // Result: true

Find out if an element has a "mystyle" class. If so, remove another class name:

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 500px;
height: 50px;
border: 1px solid black;
}
.anotherClass {
background-color: lightblue;
padding: 25px;
}
.thirdClass {
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
</style>
</head>
<body>

<p>Click the button to find out if the DIV element has a class of "mystyle". If so, remove
"anotherClass".</p>
<div id="myDIV" class="mystyle anotherClass thirdClass">
I am a DIV element
</div>
<button it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and
earlier versions.</p>

<script>
function myFunction() {
var x = [Link]("myDIV");
if ([Link]("mystyle")) {
[Link]("anotherClass");
} else {
alert("Could not find it.");
}
}
</script>
</body>
</html>

Toggle between classes to create a dropdown button:

<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>

<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button id="myBtn" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<script>
// Get the button, and when the user clicks on it, execute myFunction
[Link]("myBtn"). {myFunction()};

/* myFunction toggles between adding and removing the show class, which is used to hide and
show the dropdown content */
function myFunction() {
[Link]("myDropdown").[Link]("show");
}
</script>
</body>
</html>

HTML DOM className Property

Set the class for a <div> element with id="myDIV":

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
width: 300px;
height: 100px;
background-color: coral;
text-align: center;
font-size: 25px;
color: white;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to set a class for div.</p>
<div id="myDIV">
I am a DIV element
</div>
<button it</button>
<script>
function myFunction() {
[Link]("myDIV").className = "mystyle";
}
</script>
</body>
</html>

Definition and Usage - The className property sets or returns the class name of an element (the value of an
element's class attribute). Tip: A similar property to className is the classList property.

More Examples

Get the class name of the first <div> element in the document (if any):

var x = [Link]("DIV")[0].className;

Other examples on how to get the class name of an element:

var x = [Link]("mystyle")[0].className;
var y = [Link]("myDIV").className;

Get the class names of an element with multiple classes:

<div id="myDIV" class="mystyle test example">I am a DIV element</div>


var x = [Link]("myDIV").className;

Overwriting an existing class name with a new one:

<div id="myDIV" class="mystyle">I am a DIV element</div>


[Link]("myDIV").className = "newClassName";

To add a class to an element, without overwriting existing values, insert a space and the new class
name:

[Link]("myDIV").className += " anotherClass";

If there's a class of "mystyle" in an element with id="myDIV", change its font-size:

var x = [Link]("myDIV");
if ([Link] === "mystyle") {
[Link] = "30px";
}

Toggle between two class names. This example looks for a "mystyle" class in <div>, and if it exist,
it will be overwritten by "mystyle2":

function myFunction(){
var x = [Link]("myDIV");
// If "mystyle" exist, overwrite it with "mystyle2"
if ([Link] === "mystyle") {
[Link] = "mystyle2";
} else {
[Link] = "mystyle";
}
}

Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the
top, the class name "test" will be added to an element (and removed when scrolled up again).

<!DOCTYPE html>
<html>
<head>
<style>
.test {
background-color: yellow;
}
</style>
</head>
<body style="height:1500px">
<p>Scroll down this page</p>
<p id="myP" style="position:fixed">When you have scrolled 50 pixels from the top of this page,
add the class "test" (yellow background color) to this paragraph. Scroll up again to remove
the class.
</p>
<script>
[Link] = function() {myFunction()};
function myFunction() {
if ([Link] > 50 || [Link] > 50) {
[Link]("myP").className = "test";
} else {
[Link]("myP").className = "";
}
}
</script>
</body>
</html>

HTML DOM click() Method

Simulate a mouse-click when moving the mouse pointer over a checkbox:

<!DOCTYPE html>
<html>
<body>
<p>Hover over the checkbox to simulate a mouse-click.</p>
<form>
<input type="checkbox" id="myCheck" event
occured')">
</form>
<script>
function myFunction() {
[Link]("myCheck").click();
}
</script>
</body>
</html>

Definition and Usage - The click() method simulates a mouse-click on an element. This method can be used
to execute a click on an element as if the user manually clicked on it.

HTML DOM cloneNode() Method

Copy a <li> element from one list to another:

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>
<p>Click the button to copy an item from one list to another.</p>
<button it</button>
<p>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be
cloned.</p>
<script>
function myFunction() {
var itm = [Link]("myList2").lastChild;
var cln = [Link](true);
[Link]("myList1").appendChild(cln);
}
</script>

Definition and Usage - The cloneNode() method creates a copy of a node, and returns the clone. The
cloneNode() method clones all attributes and their values.

Tip: Use the appendChild() or insertBefore() method to insert the cloned node to the document.

Tip: Set the deep parameter value to true if you want to clone all descendants (children), otherwise false.
HTML DOM contains() Method

Find out if a <span> element is a descendant of a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="myDIV">
<p>I am a p element inside div, and I have a <span id="mySPAN"><b>span</b></span> element
inside of me.</p>
</div>
<p>Click the button to find out if the div element contains a span element.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var span = [Link]("mySPAN");
var div = [Link]("myDIV").contains(span);
[Link]("demo").innerHTML = div;
}
</script>
</body>
</html>

Definition and Usage - The contains() method returns a Boolean value indicating whether a node is a
descendant of a specified node. A descendant can be a child, grandchild, great-grandchild, and so on.

HTML DOM firstChild Property

Get the HTML content of the first child node of an <ul> element:

<p>Example list:</p>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p>Click the button to get the HTML content of the list's first child node.</p>
<button it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is
considered as nodes.</p>
<p>If you add whitespace before the first LI element, the result will be "undefined".</p>
<p id="demo"></p>
<script>
function myFunction() {
var list = [Link]("myList").[Link];
[Link]("demo").innerHTML = list;
}
</script>
Definition and Usage - The firstChild property returns the first child node of the specified node, as a Node
object. The difference between this property and firstElementChild, is that firstChild returns the first child node
as an element node, a text node or a comment node (depending on which one's first), while firstElementChild
returns the first child node as an element node (ignores text and comment nodes).

More Examples

In this example, we demonstrate how whitespace may interfere with this property.

Get the node name of the first child node of a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 15px;
}
</style>
</head>
<body>
<p>Click the button get the
node name of the DIV's first
child node.</p>
<div id="myDIV">
<p>A P element - Second child in div</p>
<span>A Span element - Fourth child in div</span>
</div>
<button it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is
considered as nodes. Therefore, in this example, the first, third and fifth child of the div
element is a #text node.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("myDIV").[Link];
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>

However, if we remove the whitespace from the source, there are no #text nodes in <div>, which
will make the <p>
element the first child
node:

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 15px;
}
</style>
</head>
<body>
<p>Click the button to get the node name of the DIV's first child node.</p>
<div id="myDIV"><p>A P element - First child in div</p><span>A Span element - Last child in
div</span></div>
<button it</button>
<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]("myDIV").[Link];
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>

Get the text of the first child node of a <select> element:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the text of the first child node of the select element.</p>
<select id="mySelect"
size="4"><option>Audi</option><option>BMW</option><option>Saab</option><option>Volvo</
option></select><br><br>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("mySelect").[Link];
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>

HTML
DOM firstElementChild Property

Get the HTML content of the first child element of an <ul> element:

<p>Example list:</p>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>Click the button to get the HTML
content of the list's first child
element.</p>
<button it</button>
<p><strong>Note:</strong> The firstElementChild property is not supported in IE8 and earlier
versions.</p>
<p id="demo"></p>
<script>
function myFunction() {
var list = [Link]("myList").[Link];
[Link]("demo").innerHTML = list;
}
</script>

Definition and Usage - The firstElementChild property returns the first child element of the specified element.
The difference between this property and firstChild, is that firstChild returns the first child node as an element
node, a text node or a comment node (depending on which one's first), while firstElementChild returns the first
child node as an element node (ignores text and comment nodes). This property is read-only.

Tip: Use the children property to return any child element of a specified element. children[0] will produce the
same result as firstElementChild.

Tip: To return the last child element of a specified element, use the lastElementChild property.

More Examples

Get the tag name of the first child element of a <div> element:

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid
black;
margin: 15px;
}
</style>
</head>
<body>
<p>Click the button to get the tag name of the DIV's first child element.</p>
<div id="myDIV">
<p>A P element - First child in div</p>
<span>A Span element - Last child in div</span>
</div>
<button it</button>
<p><strong>Note:</strong> The firstElementChild property is not supported in IE8 and earlier
versions.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("myDIV").[Link];
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>

Get the text of the first element node of a <select> element:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the text of the first child element of the select element.</p>
<select id="mySelect" size="4">
<option>Audi</option>
<option>BMW</option>
<option>Saab</option>
<option>Volvo</option>
</select>
<br><br>
<button it</button>
<p><strong>Note:</strong> The firstElementChild property is not supported in IE8 and earlier
versions.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]("mySelect").[Link];
[Link]("demo").innerHTML = x;
}
</script>
</body>
</html>

HTML
DOM focus() Method

Give focus to an <a> element:

<!DOCTYPE html>
<html>
<head>
<style>
a:focus, a:active {
color: green;
}
</style>
</head>
<body>
<a id="myAnchor" href="[Link] [Link]</a>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<input type="button" value="Get focus">
<input type="button" value="Lose focus">
<script>
function getfocus() {
[Link]("myAnchor").focus();
}
function losefocus() {
[Link]("myAnchor").blur();
}
</script>
</body>
</html>

Definition and Usage - The focus() method is used to give focus to an element (if it can be focused).

Tip: Use the blur() method to remove focus from an element.

You might also like