JavaScript
Get the Course
[Link]
JavaScript DOM Dynamic Web interactive content
INSTRUCTOR:
LAURENCE SVEKIS
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002
READY TO HELP YOU LEARN and
ANSWER ANY questions you may
have.
Course instructor : Laurence Svekis
JavaScript on Web Page
1. Create [Link] page <!doctype html>
<html>
2. Add JavaScript within html page <head>
<title>JavaScript Page</title>
3. Link to JavaScript file within </head>
HTML page <body>
<p id="idOne"></p>
4. Try the code <script>
[Link]('Hello World');
[Link]('hello');
const x = 'Hello';
[Link]("idOne").innerHTML = x;
</script>
<script src="[Link]"></script>
</body>
</html>
Get the Course [Link]
JavaScript Console Log
The Console method log() outputs a message <!doctype html>
<html>
to the web console. The message may be a <head>
single string (with optional substitution <title>JavaScript Page</title>
values), or it may be any one or more </head>
<body>
JavaScript objects. <p id="idOne">Hello World</p>
<script>
[Link] var myvar = [Link]('idOne').textContent;
[Link](myvar, "Logged!");
/API/Console/log [Link](myvar, "Logged!");
[Link](myvar, "Logged!");
[Link](myvar, "Logged!");
1. Get textContent of Element [Link](myvar, "Logged!");
[Link]('%c I see smurfs!', 'color: green; font-weight: bold;');
2. Console log messages [Link]('%c I see the sky!', 'background: blue; font-weight: bold;');
</script>
3. Console log values </body>
</html>
Get the Course [Link]
JavaScript Document Object
The Document interface represents any web <!doctype html>
<html>
page loaded in the browser and serves as an <head>
<title>JavaScript Page</title>
entry point into the web page's content, </head>
which is the DOM tree. The DOM tree includes <body>
<script>
elements such as <body> and <table>, among [Link] = "New webPage content";
[Link]([Link]);
many others. It provides functionality [Link]([Link]);
[Link](document);
globally to the document </script>
[Link] </body>
</html>
/API/Document
1. Select the document body - update
page contents
2. View the document and body in the
console using dir and log.
Get the Course [Link]
JavaScript WEBSITE DOM
<!DOCTYPE html><html><head> <title>JavaScript DOM</title></head><body> <nav role="navigation" class="navbar
Selecting the elements on the page is the navbar-default"> <div class="navbar-header"> <button type="button" data-target="#navbarCollapse"
data-toggle="collapse" class="navbar-toggle"> <span class="sr-only">Toggle navigation</span> <span
first step before manipulating the element. class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#"
class="navbar-brand">Home Page</a> </div> <div id="navbarCollapse" class="collapse navbar-collapse"> <ul
There are a number of ways to make element class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a
href="#">Contact</a></li> </ul> </div> </nav> <div class="container"> <h1 id="header">Welcome to My Website</h1>
selections. <div id="topSection" class="row"> <p><span class="second">A</span> This is my website which <span
class="first">can</span> change!</p> <p><span class="second">B</span> Are you going to see what <a
href="[Link] happens when the word <span class="first">can</span>
changes?</p> <p><span class="second">C</span> Elements can <a href="[Link]
JS</a> change and you <span class="first">can</span> select them by Class, ID and other methods.</p> <div
1. Create a website with a number of class="first"><span class="second">D</span> This is a Div with the class that is the same as the spans</div> </div>
<div id="outPut" class="row"> <p id="outputContent" class="outputClass"> This is where the content will change!!!
<span class="first">span</span> <span class="first">This is just a new div</span></p> </div> <div class="row"> <p>
elements you can use the website Buttons</p> <button id="btnA">Button A</button> <button id="btnB">Button B</button> <button id="btnC">Button
C</button> </div> <div class="row"> <p> Lists</p> <ul> <li id="listA" class="listClass">List A</li> <li id="listB"
code posted on the right → class="listClass">List B</li> <li id="listC" class="listClass">List C</li> <li id="listD" class="listClass">List D</li> <li
id="listE" class="listClass">List E</li> </ul> </div> <div class="row"> <p> Form</p> <form> Name : <input
name="firstName" type="text" id="firstName" value="firstName value"> <br> Email : <input name="email" type="email"
2. Update the script files select id="email"> <br> <input name="submitButton" type="submit" id="submitButton"> </form> </div> <div class="row"> <p>
Images Links</p> <p>We had to place some links to <a href="[Link] websites </a> </p> <p>
the element with id header and Update this code to improve on the site experience. This is just a second <span class="second">span</span> <span
class="second">This is another new div</span> In this section we added some images</p> <p> <img id="myImage"
src="[Link] alt="temp image"> </p> </div> <div id="footer" class="row"> <div> Copyright ©
update the textContent [Link] </div> </div> </div> <script src="[Link]"></script></body></html>
const header = [Link]('header');
[Link](header);
[Link] = 'New header Content';
Get the Course [Link]
JavaScript Selecting by TAG
The [Link]() method const el1 = [Link]('h1');
[Link] = 'First H1 on Page';
returns a live HTMLCollection of elements [Link](el1);
const el2 = [Link]('h1'); // return HTMLcollection
with the given tag name. All descendants of [Link] = 'First H1 by Tag';
[Link](el2);
the specified element are searched, but not el2[0].textContent = 'First H1 by Tag';
the element itself. The returned list is [Link](el2[0]);
live, which means it updates itself with the
DOM tree automatically. Therefore, there is
no need to call
[Link]() with the same
element and arguments repeatedly if the DOM
changes in between calls.
1. Select the element in different
ways
2. Update the textContent
Get the Course [Link]
JavaScript QUERYSELECTOR
The Document method querySelector() returns const el1 = [Link]('h1');
[Link] = 'First H1 on Page';
the first Element within the document that const el2 = [Link]('.second');
[Link] = 'First element with class of second';
matches the specified selector, or group of const el3 = [Link]('#btnA');
[Link] = 'Element with matching id';
selectors. If no matches are found, null is
returned.
[Link]
/API/Document/querySelector
1. Select by tag
2. Select by class .
3. Select by id #
Get the Course [Link]
JavaScript QUERYSELECTORALL
The Document method querySelectorAll() const els1 = [Link]('p');
[Link](els1);
returns a static (not live) NodeList const els2 = [Link]('p .second');
[Link](els2);
representing a list of the document's const els3 = [Link]("div .first"); /// css selector
elements that match the specified group of [Link](els3);
for (var i = 0; i < [Link]; i++) {
selectors. [Link](els3[i]);
els3[i].innerHTML = els3[i].textContent + ' <b>' + i + '</b>';
[Link] }
/API/Document/querySelectorAll
1. Select by tag
2. Select by class .
3. Loop elements from nodelist
Get the Course [Link]
JavaScript QUERYSELECTORALL
You can use CSS type selectors to pinpoint const myValues = [Link]("a[href*=\"JS\"]");
for (var i = 0; i < [Link]; i++) {
the elements, including selecting by [Link](myValues[i].innerHTML);
myValues[i].textContent = "THIS IS CHANGED " + i;
attributes and more. myValues[i].href = "[Link]
Also Select only elements from the parent. }
const container = [Link]("[Link]");
[Link](container);
const matches = [Link]("[Link] ");
1. Select all the have href linking [Link](matches);
[Link](matches[0]);
to JS in the URL.
2. Use the parent selection element
as the object to select from.
Get the Course [Link]
JavaScript Update Attributes
Select all the images and update height and const myImgs = [Link]("img");
for (var i = 0; i < [Link]; i++) {
title. myImgs[i].height = 20;
myImgs[i].title = myImgs[i].alt;
}
1. Selection of page images
2. Update attributes
Get the Course [Link]
JavaScript childNodes Children
List out children and childnodes from const uList = [Link]('ul')[1];
[Link](uList);
selected element. View node types. [Link]([Link]);
[Link]([Link]);
[Link] for (var i = 0; i < [Link]; i++) {
[Link]([Link][i]);
ocs/Web/API/Node/nodeType [Link]([Link][i].nodeType);
}
for (var i = 0; i < [Link]; i++) {
[Link]([Link][i]);
1. Select children and childnodes of [Link]([Link][i].nodeType);
}
same element. const myDiv = [Link]('li');
[Link](myDiv);
2. Note nodeType of each for (var i = 0; i < [Link]; i++) {
[Link](myDiv[i].[Link]);
3. Get data of selected element }
var dList = [Link]('div')[3];
[Link](dList);
[Link]([Link][1]);
[Link]([Link][1].childNodes[1]);
Get the Course [Link]
JavaScript ELEMENT STYLE UPDATE
The [Link] property is used to const headerElement = [Link]("header");
[Link] = 'This is my new Header';
get as well as set the inline style of an [Link] = 'blue';
[Link] = "yellow";
element. [Link] = 'Cambria, "Hoefler Text", "Liberation Serif", Times,
[Link] "Times New Roman", serif';
[Link] = '5px solid black';
/API/HTMLElement/style
1. Select an element
2. Update its style
Get the Course [Link]
JavaScript Multiple ELEMENT STYLE UPDATE
The [Link] property is used to const rowElement = [Link]("row");
for (var i = 0 ; i < [Link]; i++) {
get as well as set the inline style of an rowElement[i].[Link] = "center";
rowElement[i].[Link] = 'blue';
element. rowElement[i].[Link] = "red";
[Link] rowElement[i].[Link] = 'Cambria, "Hoefler Text", "Liberation Serif", Times,
"Times New Roman", serif';
/API/HTMLElement/style rowElement[i].[Link] = '1px solid black';
}
1. Select an elements
2. Update their style
Get the Course [Link]
JavaScript Add Class to Element
Create a class with some styling. <style>
.newStyle {
The className property of the Element color: #F8373B;
background-color: #FAFFCE;
interface gets and sets the value of text-align: center;
font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New
the class attribute of the specified Roman", serif;
}
element. The [Link] is a .red{
.blue{
color:red;
color:blue;
}
}
read-only property that returns a </style>
live DOMTokenList collection of the
const rowElement = [Link](".row");
class attributes of the element. for (var i = 0; i < [Link]; i++) {
rowElement[i].className += " newStyle";
[Link] }
[Link](function (el, index) {
ocs/Web/API/Element/className [Link](el);
[Link](index);
[Link] [Link]('red');
[Link]('blue');
ocs/Web/API/Element/classList [Link]('row');
})
Get the Course [Link]
JavaScript SetAttribute
Sets the value of an attribute on the const btn= [Link]('button');
[Link]('id','myButton');
specified element. If the attribute [Link]([Link]);
already exists, the value is updated;
otherwise a new attribute is added
with the specified name and value.
To get the current value of an
attribute, use getAttribute(); to
remove an attribute, call
removeAttribute().
[Link]
ocs/Web/API/Element/setAttribute
Get the Course [Link]
JavaScript createElement Add New Element
In an HTML document, the const ul = [Link]('.row ul');
const li = [Link]("li");
[Link]() method [Link]([Link]("List F"));
[Link]("id","listF");
creates the HTML element specified by [Link]("red");
[Link](li);
tagName, or an HTMLUnknownElement if [Link](li);
tagName isn't recognized.
[Link]
ocs/Web/API/Document/createElement
Get the Course [Link]
JavaScript Append and ++
The [Link]() method adds a const vals = [200, 400, 500];
const main = [Link]('.container');
node to the end of the list of [Link](function (v) {
let html = '<img src="[Link] + v + 'x100/0000ff"><br>';
children of a specified parent node. [Link] += html;
[Link](html);
})
[Link](function (v) {
[Link] let img = [Link]('img');
[Link] = '[Link] + v + 'x100/00ff00';
ocs/Web/API/Node/appendChild [Link](img);
[Link](img); // same object can only be in one place!!!
})
Get the Course [Link]
JavaScript addEventListener
The EventTarget method const myButton = [Link]("btnA");
const myOutput = [Link]('.container');
addEventListener() sets up a function const btnClick = function () {
[Link] = "You clicked the first button!";
that will be called whenever the };
[Link]("click", btnClick);
specified event is delivered to the
target.
[Link]
ocs/Web/API/EventTarget/addEventListe
ner
Get the Course [Link]
JavaScript addEventListenerS
useCapture = true const myBtns = [Link]('button');
const myOutput = [Link]('.container');
let cnt = 0;
for (var i = 0; i < [Link]; i++) {
The handler is set on the capturing myBtns[i].addEventListener('click', btnClick, false);
}
phase. Events will get to it before
function btnClick(e) {
getting to its children. cnt++;
[Link](e);
[Link](this);
[Link]([Link]);
useCapture = false.- default [Link] = 'red';
[Link] = "You clicked this button <" + cnt + ">";
};
The handler is set on the bubbling
phase. Events will get to it after
getting to its children.
Get the Course [Link]
JavaScript MOUSEMOVE
Select the element to apply event const myOutput = [Link]('.container');
const header = [Link]('#header');
listener on. Use mouse move and get const mouseMover = function (e) {
[Link](e);
the position. [Link](e.x);
[Link] = "x is at " + e.x + " y is at " + e.y;
};
[Link]("mousemove", mouseMover);
Get the Course [Link]
JavaScript MOUSEMOVE on Image Do something
Make some images. Detect mouse const num = 10;
const output = [Link]('div');
movements on images. const myOutput = [Link]('.container');
[Link]('class', 'red');
1. Create number of images [Link] = '3em';
[Link] = "welcome";
dynamically [Link](output);
for (let x = 0; x < num; x++) {
2. Select all page images let img = [Link]('img');
let clr = [Link]().toString(16).substr(-6);
3. Add event listeners to all images [Link] = '[Link] + clr;
[Link](img);
for mouse over and mouse out }
const myImages = [Link]('img');
4. Update output element background [Link](function (el) {
[Link]("mousemove", mouseMover);
with image background color. [Link]("mouseleave", mouseMoverOut);
})
function mouseMover(e) {
[Link] = "You are over the image!!! " + [Link](-6);;
[Link] = '#' + [Link](-6);
};
function mouseMoverOut(e) {
[Link] = "You moved off the image " + [Link](-6);;
[Link] = "white";
};
Get the Course [Link]
JavaScript FORM VALUES
The Event interface's const myOutput = [Link]("header");
const myButton = [Link]("submitButton");
preventDefault() method tells the const btnClick = function (e) {
[Link]();
user agent that if the event does not let messageOut;
let name = [Link]("firstName").value;
get explicitly handled, its default let email = [Link]("email").value;
if (name) {
action should not be taken as it messageOut = "Hello " + name;
}
normally would be. else {
messageOut = "Mysterious person I wonder why you don't add your name.";
[Link] }
[Link] = messageOut;
ocs/Web/API/Event/preventDefault };
[Link]("click", btnClick);
1. Select the value from a form
2. Prevent default on form submit
Get the Course [Link]
JavaScript a link stopper
Use prevent default to stop all links const links = [Link]('a');
[Link](function(el){
from being clickable on the page. [Link]('click',function(e){
[Link]()
[Link](e);
[Link]('clicked');
1. Select all hyperlinks [Link]([Link]('href'));
})
2. Add prevent default })
Get the Course [Link]
JavaScript WINDOW OBJECT
The Window interface represents a [Link](window);
///Window Object Properties
window containing a DOM document; the [Link]([Link]);
[Link]([Link]);
document property points to the DOM [Link]([Link]);
[Link]([Link]);
document loaded in that window. [Link]([Link]);
[Link] ///Window Object Methods
[Link]("", "", "width=100, height=100");
ocs/Web/API/Window [Link](250, 250);
setInterval(function(){ [Link]("This message will show every 5 seconds"); }, 5000);
1. Open new window
Get the Course [Link]
JavaScript Annoying Blinker
Select all the buttons on the page let blinky;
const myButton = [Link]("submitButton");
that will stop the text blinking const myOutput = [Link]('.container');
const btns = [Link]('button');
colors. [Link](function (el) {
[Link]("click", stopChangeText);
})
blinky = setInterval(changeText, 100);
1. Create interval that updates main
function changeText() {
element background and color [Link] = [Link] == "red" ? "black" : "red";
[Link] = '#' + [Link]().toString(16).substr(-6);
2. Add eventlisteners to all buttons }
on the page function stopChangeText(e) {
[Link]();
3. Click button stop the blinking clearInterval(blinky);
}
Get the Course [Link]
JavaScript ANIMATIONS :)
The [Link]() let stopper = false;let dir = 1;
const mover = [Link]('div');
method tells the browser that you const myOutput = [Link]('.container');
[Link] = 'absolute';[Link] = '10px';[Link] =
wish to perform an animation and '100px';[Link] = 'red';[Link] =
'20px';[Link] = 'catch me';[Link] = 'white';
requests that the browser call a [Link]('click', animateMe);
[Link](mover);
specified function to update an let animator = [Link](render);
function animateMe(e) {
animation before the next repaint. if (stopper) {
animator = [Link](render);
stopper = false;
[Link](dir);
1. Create an element dir *= -1;
}
2. Animate it else {
[Link](animator);
3. Add event listener to toggle stopper = true;
}
direction }
function render() {
let pos = [Link];
[Link](pos);
[Link] = (pos + dir) + "px";
animator = [Link](render);
}
Get the Course [Link]
Congratulations on completing the course!
Thank you for your support
Check out more about JavaScript at MDN. [Link]
Find out more about my courses at [Link]
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.
Get the Course
[Link]