You are on page 1of 48

HTML DOM

DOCUMENT OBJECT MODEL


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 react to all the EVENTS in the page
When a web page is loaded, the browser creates a Document Object Model of the page.
1
FINDING HTML ELEMENTS
Id
Tag Name
Class Name
Query Selector
FINDING HTML
ELEMENTS
id finding-id.html HTML RESULT

<h1 id=“head”>ID Heading</h1> <h1 id=“intro”>ID Heading</h1>


Often, with JavaScript, you want
to manipulate HTML elements. To <script>
do so, you have to find the
var intro = document.getElementById(“head”);
elements first.
console.log(intro);
</script>
FINDING HTML
ELEMENTS
HTML finding-tag-name.html RESULT tag name
<p>This is a tag paragraph.</p> <p>This is a tag paragraph.</p>
Often, with JavaScript, you want
to manipulate HTML elements. To
<script> do so, you have to find the
var p = document.getElementsByTagName(“p”)[0]; elements first.
console.log(p);
</script>
FINDING HTML
ELEMENTS
class name finding-class-name.html HTML RESULT

<p class=“para”>This is a class paragraph.</p> <p class=“para”>This is a class paragraph.</p>


Often, with JavaScript, you want
to manipulate HTML elements. To <script>
do so, you have to find the
var para = document.getElementsByClassName
elements first.
(“para”)[0];
console.log(para);
</script>
FINDING HTML
ELEMENTS
HTML finding-query-selector.html RESULT querySelectorAll
<p>Paragraph</p> NodeList(3) [p, p.para, p#para] Often, with JavaScript, you want
<p class=“para”>Class paragraph</p>
to manipulate HTML elements. To
<p id=“para”>ID paragraph</p>
do so, you have to find the
elements first.
<script>
var p = document.querySelectorAll(“p”);
console.log(p);
</script>
2
CHANGING HTML CONTENT

Text Content
Inner HTML
CHANGING HTML
CONTENT
textContent text-content.html HTML RESULT

<p id=“para”></p> Hello World


PURE TEXT
<script>
The easiest way to modify the var para = document.getElementById(“para”);
content of an HTML element is by box.textContent = “Hello World”;
using the textContent property. </script>
CHANGING HTML
CONTENT
HTML inner-html.html RESULT innerHTML
<p id=“para”></p> Hello World Again!
The easiest way to modify the
content of an HTML element is by
<script> using the textContent property.
var para = document.getElementById(“para”);
box.innerHTML = “Hello World Again!”;
</script>
3
CHANGING HTML ELEMENTS STYLE

HTMLElement.style
HTMLElement.style.cssText
CHANGING HTML
ELEMENTS STYLE
ele.style changing-style1.html HTML RESULT

<h1 id=“head”>Heading Style</h1> Heading Style


The style property returns a
CSSStyleDeclaration object, which <script>
represents an element's style
var head = document.getElementById(“head”);
attribute.
head.style.color = “red” ;
</script>
CHANGING HTML
ELEMENTS STYLE
HTML changing-style2.html RESULT ele.style.cssText
<span id=“text”>Heading Style</span> Heading Style The style property returns a
CSSStyleDeclaration object, which
<script> represents an element's style
var text = document.getElementById(“text”); attribute.
text.style.cssText = “color: white; background:
red” ;
</script>
4
MODIFYING THE CLASS

Add Class
Remove Class
MODIFYING THE
CLASS
classList.add() add-class.html HTML RESULT

className <style>
.red { color: red; }
Red
Green
.green { color: green; }
</style>
Add a class name to an element
with JavaScript. <h1>Red</h1>
<h2>Green</h2>

<script>
var h1 = document.querySelector(“h1”);
h1.classList.add(“red”);

var h2 = document.querySelector(“h2”);
h2.className = “green”;
</script>
MODIFYING THE
CLASS
HTML remove-class.html RESULT classList.remove()
<style> Red className
.red { color: red; } Green
.green { color: green; } Remove a class name from an
.remove { color: inherit; } element with JavaScript.
</style>

<h1 class=“red”>Red</h1>
<h2 class=“green”>Green</h2>

<script>
var h1 = document.querySelector(“h1”);
h1.classList.remove(“red”);

var h2 = document.querySelector(“h2”);
h2.className = “remove”; // override class
</script>
5
ATTRIBUTES & PROPERTIES
hasAttribute(name)
getAttribute(name)
setAttribute(name, value)
removeAttribute(name)
ATTRIBUTES &
PROPERTIES
HTML html-attribute.html HTML RESULT

<body id=“body-id” hello=“world”></body> body-id


attributes <script>
undefined

An element has id or another console.log(document.body.id);


standard attribute, the console.log(document.body.hello);
corresponding property gets </script>
created.

But that doesn’t happen if the


attribute is non-standard.
ATTRIBUTES &
PROPERTIES
HTML has-attribute.html RESULT hasAttribute(name)
<div id=“box” hello=“world”></div> true Checks for existence.

<script>
var box = document.getElementById(“box”);
console.log(box.hasAttribute(“hello”));
</script>
ATTRIBUTES &
PROPERTIES
getAttribute(name) get-attribute.html HTML RESULT

Gets the value. <div id=“box” hello=“world”></div> world

<script>
var box = document.getElementById(“box”);
console.log(box.getAttribute(“hello”));
</script>
ATTRIBUTES &
PROPERTIES
HTML set-attribute.html RESULT setAttribute(name, value)

<div id=“box”></div> world Sets the value.

<script>
var box = document.getElementById(“box”);
box.setAttribute(“hello”, “world”);
console.log(box.getAttribute(“hello”));
</script>
ATTRIBUTES &
PROPERTIES
removeAttribute(name) remove-attribute.html HTML RESULT
Removes the value. <div id=“box” hello=“world”></div> false

<script>
var box = document.getElementById(“box”);
box.removeAttribute(“hello”);
console.log(box.hasAttribute(“hello”));
</script>
6
CHANGING HTML ATTRIBUTE
CHANGING HTML
ATTRIBUTE
To change the attribute of an
HTML element. change-html-attribute.html HTML RESULT

<img src=“apple.jpg” alt=“Apple”>

<script>
var img = document.querySelector(“img”);
img.src = “orange.jpg”;
</script>
7
CREATING HTML ELEMENTS

Creating new HTML elements


Removing existing HTML elements
CREATING NEW HTML
ELEMENTS
Creation Methods
creating-new-element.html HTML RESULT
createElement
<div id=“wrap”></div> Hello
createTextNode
<script>
var wrap = document.getElementById(“wrap”);
Insertion Methods var p = document.createElement(“p”);
appendChild var text = document.createTextNode(“Hello”);
p.appendChild(text);
append/prepend wrap.appendChild(p);
</script>

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.
REMOVING EXISTING HTML
ELEMENTS
HTML remove-element.html RESULT removeChild
<div id=“wrap”> Paragraph
To remove an HTML element, you
<h1 class=“para”>Heading</h1>
<p class=“para”>Paragraph</p> must know the parent of the
element.
</div>

<script>
var wrap = document.getElementById(“wrap”);
var para = document.querySelector(“h1.para”);

wrap.removeChild(para);
</script>
8
EVENTS

Mouse, Form, Keyboard, Document, CSS events, etc.,


Event handlers
Event object
EVENTS
Event handlers events-handlers.html HTML RESULT

<h3>Mouse events</h3>
To react on events we can assign a
<h3>Form events</h3>
handler – a function that runs in <h3>Keyboard events</h3>
case of an event.
<h3>Document events</h3>
<h3>CSS events</h3>
Handlers are a way to run
JavaScript code in case of user
actions.
EVENTS
HTML Attribute
HTML html-event-attribute-1.html RESULT

<button onclick=“alert(‘Click!’);”>Click Me</button>


onclick
A JavaScript can be executed when
an event occurs, like when a user
clicks on an HTML element.

When a user clicks on button.


EVENTS
HTML Attribute
html-event-attribute-2.html HTML RESULT
onclick <button onclick=“callClick(’)”>Click Me</button>
An HTML-attribute is not a <script>
convenient place to write a lot of
code, so we’d better create a function callClick() {
JavaScript function and call it callClick(“Click!”);
there. };
</script>
EVENTS
DOM Property
HTML dom-property-1.html RESULT

<button id=“btn”>Click Me</button>


.onclick
<script> We can assign a handler using a
DOM property on<event>.
var btn = document.getElementById(“btn”);

btn.onclick = function() {
alert(“Click”);
};
</script>
EVENTS
DOM Property
dom-property-2.html HTML RESULT
.onclick <button id=“btn” onclick=“alert(‘Before’);”>
Click Me
OVERWRITE Handler </button>

As there’s only one onclick <script>


property, we can’t assign more var btn = document.getElementById(“btn”);
than one event handler.

In the example below adding a btn.onclick = function() {


handler with JavaScript overwrites alert(“After”);
the existing handler: };
</script>
EVENTS
Accessing the elements
HTML accessing-this.html RESULT

<button onclick=“alert(this.innerHTML);”>
this
Click Me
</button> The value of this inside a handler is
the element. The one which has
the handler on it.
EVENTS
addEventListener addeventlistener.html HTML RESULT

The fundamental problem of the <button id=“btn”>Click Me</button>


aforementioned ways to assign
handlers – we can’t assign multiple <script>
handlers to one event. var btn = document.getElementById(“btn”);

btn.addEventListener(‘click’, function() {
alert(“First”);
});

btn.addEventListener(‘click’, function() {
alert(“Second”);
});

</script>
EVENTS
HTML event-object.html RESULT object
<button id=“btn”>Click Me</button>
To properly handle an event we’d
<script> want to know more about what’s
happened. Not just a “click” or a
var btn = document.getElementById(“btn”); “keypress”, but what were the
pointer coordinates? Which key was
btn.addEventListener(‘click’, function(e) { pressed? And so on.
console.log(e);
When an event happens, the
});
browser creates an event object,
puts details into it and passes it as
</script> an argument to the handler.
9
FORM CONTROLS
Form properties and methods
Focusing: focus/blur
Events: change, input
Forms: event and method submit
FORM
PROPERTIES & METHODS
document.forms forms-elements-1.html HTML RESULT

Document forms are members of <form name=“myform”> <input type=“text” name=“username”>


<input type=“text” name=“username”>
the special collection
</form>
document.forms.
<script>
When we have a form, then any
element is available in the named var form = document.forms.myform;
collection form.elements. var username = form.elements.username;

console.log(username);
</script>
FORMS
PROPERTIES & METHODS
HTML forms-elements-2.html RESULT element.form
<form id=“myform”> <input type=“text” name=“username”>
For any element, the form is
<input type=“text” name=“username”>
</form> available as element.form. So a
form references all elements, and
elements reference the form.
<script>
var username = myform.username;

console.log(username);
</script>
FOCUSING
focus() focus.html HTML RESULT

<form id=“myform”>
An element receives a focus when
<input type=“text” name=“username”>
the user either clicks on it or uses </form>
the Tab key on the keyboard.
<script>
There’s also an autofocus HTML
attribute that puts the focus into myform.username.focus();
an element by default when a page </script>
loads and other means of getting a
focus.
FOCUSING
HTML blur.html RESULT blur
<form id=“myform”> <input type=“text” name=“username”>
The moment of losing the focus
<input type=“text” name=“username”>
(“blur”) can be even more
</form>
important.
<script>
That’s when a user clicks
var username = myform.username; somewhere else or presses Tab to
go to the next form field, or there
username.onblur = () => { are other means as well.
if ( username.value === “” )
alert(“Enter user name!”);
else
alert(“Success”);
};
</script>
EVENTS
change change-event.html HTML RESULT

<input type=“text” id=“msg”>


The change event triggers when
<p id=“show”></p>
the element has finished changing.
<script>
For text inputs that means that the
event occurs when it loses focus. var message = document.getElementById(“msg”);
var show = document.getElementById(“show”);

message.addEventListener(‘change’, function() {
show.innerHTML = message.value;
});
</script>
EVENTS
HTML event-input.html RESULT input
<input type=“text” id=“msg”>
The input event triggers every time
<p id=“show”></p>
after a value is modified by the
user.
<script>
var message = document.getElementById(“msg”); Unlike keyboard events, it triggers
var show = document.getElementById(“show”); on any value change, even those
that does not involve keyboard
message.addEventListener(‘input’, function() { actions: pasting with a mouse or
using speech recognition to dictate
show.innerHTML = message.value;
the text.
});
</script>
FORMS
Event: submit event-submit-prevent.html HTML RESULT

<form id=“myform”>
The submit event triggers when
<input type=“submit” value=“Submit”>
the form is submitted, it is usually </form>
used to validate the form before
sending it to the server or to abort
<script>
the submission and process it in
JavaScript. myform.onsubmit = function(e) => {
e.preventDefault();
The handler can check the data, };
and if there are errors, show them </script>
and call event.preventDefault(),
then the form won’t be sent to the
server.
FORMS
HTML event-submit-false.html RESULT Event: submit
<form id=“myform” onsubmit=“alert(“Submit!”);
Form is not sent anywhere due to
return false;”>
return false.
<input type=“submit” value=“Submit”>
</form>
FORMS
Method: submit method-submit.html HTML RESULT

<script>
To submit a form to the server
manually, we can call var form = document.createElement(“form”);
form.submit(). form.action = “https://www.google.com”;
form.method = “GET”;
Then the submit event is not
generated. It is assumed that if the
document.body.append(form);
programmer calls form.submit(),
then the script already did all
related processing. form.submit();
</script>
10
STORING DATA IN THE BROWSER

LocalStorage: setItem(key, value), getItem(key), removeItem(key), clear()


STORING DATA
IN THE BROWSER
localStorage localstorage.html HTML RESULT

<script> John
localStorage.setItem(“first_name”, “John"); null
setItem(key, value) localStorage.setItem(“last_name”, “Doe");
getItem(key)
removeItem(key) console.log(localStorage.getItem(“fist_name”);
clear()
localStorage.removeItem(“fist_name”);
console.log(localStorage.getItem(“fist_name”);
The data does not expire. It </script>
remains after the browser restart
and even OS reboot.

You might also like