Route Academy
JavaScript Basics: Week 3
A Guide for Beginners
Prepared for Students at Route Academy
May 2025
JavaScript Basics - Route Academy Week 3
Contents
1 Welcome to Week 3 of JavaScript! 2
2 Regex (Regular Expressions): The Text Detective 2
2.1 Basic Regex Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Using Regex in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.3 Example 1: Validating a Password . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.4 Example 2: Finding All Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.5 Example 3: Replacing Spaces with Dashes . . . . . . . . . . . . . . . . . . . . . 3
2.6 Example 4: Checking for a Valid Email Pattern . . . . . . . . . . . . . . . . . . 3
3 DOM (Document Object Model): The Map of Your Webpage 3
3.1 DOM Selectors: Finding Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Changing HTML, Styles, and Classes . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.1 Changing HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.2 Changing Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2.3 Managing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Managing Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4 Events: Listening to User Actions 10
4.1 Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.2 Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.3 Input Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1
JavaScript Basics - Route Academy Week 3
1 Welcome to Week 3 of JavaScript!
Hello, Route Academy superstars! We’ve learned so much in Weeks 1 and 2—variables,
functions, objects, arrays, and more. This week, we’re diving into some powerful tools!
We’ll learn how to search and validate text with regular expressions, make our webpages
interactive by exploring the DOM, and respond to user actions with events. Let’s make
coding even more fun with lots of exciting examples!
2 Regex (Regular Expressions): The Text Detective
A regular expression (or regex) is like a super-smart detective that helps you find patterns
in text. You can use it to search for specific characters, validate input, or replace text.
2.1 Basic Regex Patterns
Here are some common regex patterns you can use:
• [a-z]: Finds any lowercase letter from a to z.
• [A-Z]: Finds any uppercase letter from A to Z.
• [0-9]: Finds any digit from 0 to 9.
• ? or {0,1}: Matches zero or one occurrence of a character.
• * or {0,}: Matches zero or more occurrences of a character.
• + or {1,}: Matches one or more occurrences of a character.
• \s: Matches any whitespace (like spaces or tabs).
• \w: Matches any word character (letters, digits, or underscores).
• \d: Matches any digit (same as [0-9]).
• .: Matches any character except a newline.
2.2 Using Regex in JavaScript
You can use regex with methods like test() to check if a pattern exists, or match() to
find matches.
1 var text = "Hello 123!";
2 var hasLowercase = /[a-z]/. test(text);
3 console .log( hasLowercase ); // Output : true ( because " Hello " has
lowercase letters )
4
5 var hasDigits = /[0 -9]/. test(text);
6 console .log( hasDigits ); // Output : true ( because "123" has digits )
7
8 var digits = [Link] (/\d+/);
9 console .log( digits ); // Output : ["123"] ( finds one or more digits )
2
JavaScript Basics - Route Academy Week 3
2.3 Example 1: Validating a Password
Let’s create a function to check if a password has at least one letter and one number.
1 function checkPassword ( password ) {
2 var hasLetter = /[a-zA -Z]/. test( password );
3 var hasNumber = /\d/. test( password );
4 if ( hasLetter && hasNumber ) {
5 return " Password is good !";
6 } else {
7 return " Password needs at least one letter and one number !";
8 }
9 }
10 console .log( checkPassword (" abc123 ")); // Output : Password is good!
11 console .log( checkPassword (" abc ")); // Output : Password needs at
least one letter and one number !
2.4 Example 2: Finding All Words
Let’s find all words in a sentence using \w+.
1 var sentence = "I love Route Academy !";
2 var words = sentence . match (/\w+/g); // The "g" flag finds all
matches
3 console .log(words); // Output : ["I", "love", " Route ", " Academy "]
2.5 Example 3: Replacing Spaces with Dashes
Let’s replace all spaces with dashes using \s.
1 var phrase = "Route Academy is great ";
2 var dashedPhrase = phrase . replace (/\s/g, " -");
3 console .log( dashedPhrase ); // Output : Route -Academy -is - great
2.6 Example 4: Checking for a Valid Email Pattern
Let’s check if a string looks like an email (simplified).
1 function isEmailValid ( email ) {
2 var emailPattern = /[a-zA -Z0 -9]+@[a-zA -Z ]+\.[a-zA -Z]{2 ,}/;
3 return emailPattern .test( email );
4 }
5 console .log( isEmailValid (" student@route .com ")); // Output : true
6 console .log( isEmailValid (" invalid - email ")); // Output : false
3 DOM (Document Object Model): The Map of Your Webpage
When a webpage loads, the browser creates a Document Object Model (DOM), which is
like a map of your page. It turns your HTML into a tree of objects that JavaScript can
interact with.
3
JavaScript Basics - Route Academy Week 3
3.1 DOM Selectors: Finding Elements
You can find elements on the page using different methods:
• [Link]("elementID"): Finds an element by its ID.
• [Link]("p"): Finds all <p> elements (returns a collec-
tion).
• [Link]("item"): Finds all elements with class item
(returns a collection).
• [Link]("gender"): Finds all elements with name="gender"
(returns a node list).
• [Link](".lessonBlock"): Finds all elements matching a
CSS selector (returns a node list).
• [Link](".lessonBlock"): Finds the first element matching a
CSS selector.
1 <!-- HTML -->
2 <p id=" greetingText ">Hello , Route Academy !</p>
3 <p class =" lessonBlock "> Welcome to Week 3</p>
4 <p class =" lessonBlock ">’Lets learn DOM !</p>
5 <input type =" radio" name =" userGender " value =" male">
6 <input type =" radio" name =" userGender " value =" female ">
7
8 <!-- JavaScript -->
9 var message = document . getElementById (" greetingText ");
10 console .log( message . innerHTML ); // Output : Hello , Route Academy !
11
12 var paragraphs = document . getElementsByTagName ("p");
13 console .log( paragraphs . length ); // Output : 3 ( there are 3 <p> tags)
14
15 var lessonBlocks = document . getElementsByClassName (" lessonBlock ");
16 console .log( lessonBlocks [0]. innerHTML ); // Output : Welcome to Week 3
17
18 var genderInputs = document . getElementsByName (" userGender ");
19 console .log( genderInputs . length ); // Output : 2 (two radio inputs )
20
21 var firstLessonBlock = document . querySelector (". lessonBlock ");
22 console .log( firstLessonBlock . innerHTML ); // Output : Welcome to Week
3
23
24 var allLessonBlocks = document . querySelectorAll (". lessonBlock ");
25 console .log( allLessonBlocks . length ); // Output : 2
Example 1: Selecting a Header by ID
1 <!-- HTML -->
2 <h1 id=" mainHeader "> Route Academy </h1 >
3
4
JavaScript Basics - Route Academy Week 3
4 <!-- JavaScript -->
5 var header = document . getElementById (" mainHeader ");
6 console .log( header . innerHTML ); // Output : Route Academy
7 header . innerHTML = " Welcome to Route Academy !";
Example 2: Finding All Images by Tag Name
1 <!-- HTML -->
2 <img src =" image1 .jpg" alt =" Image 1">
3 <img src =" image2 .jpg" alt =" Image 2">
4
5 <!-- JavaScript -->
6 var images = document . getElementsByTagName (" img ");
7 console .log( images . length ); // Output : 2
8 console .log( images [0]. getAttribute (" src ")); // Output : image1 .jpg
Example 3: Selecting Elements by Class Name
1 <!-- HTML -->
2 <div class =" card">Card 1</div >
3 <div class =" card">Card 2</div >
4 <div class =" card">Card 3</div >
5
6 <!-- JavaScript -->
7 var cards = document . getElementsByClassName (" card ");
8 for (var i = 0; i < cards . length ; i++) {
9 cards [i]. style. border = "1 px solid black ";
10 }
11 console .log(cards. length ); // Output : 3
Example 4: Finding Inputs by Name
1 <!-- HTML -->
2 <input type =" checkbox " name =" hobby " value =" reading ">
3 <input type =" checkbox " name =" hobby " value =" gaming ">
4
5 <!-- JavaScript -->
6 var hobbies = document . getElementsByName (" hobby ");
7 console .log( hobbies . length ); // Output : 2
8 console .log( hobbies [1]. value ); // Output : gaming
Example 5: Using querySelector with Different Selectors
1 <!-- HTML -->
2 <div class =" sidebar ">Sidebar </div >
3 <button class =" actionBtn ">Click </ button >
4 <span data -id ="123" > Data </ span >
5
6 <!-- JavaScript -->
7 var sidebar = document . querySelector (". sidebar ");
8 console .log( sidebar . innerHTML ); // Output : Sidebar
9
10 var button = document . querySelector (". actionBtn ");
11 button . style. backgroundColor = " yellow ";
5
JavaScript Basics - Route Academy Week 3
12
13 var dataElement = document . querySelector ("[ data -id = '123 ']");
14 console .log( dataElement . innerHTML ); // Output : Data
Example 6: Using querySelectorAll to Style Multiple Elements
1 <!-- HTML -->
2 <li class =" navItem ">Home </li >
3 <li class =" navItem ">About </li >
4 <li class =" navItem ">Contact </li >
5
6 <!-- JavaScript -->
7 var navItems = document . querySelectorAll (". navItem ");
8 navItems . forEach ( function (item) {
9 item. [Link] = "blue ";
10 });
11 console .log( navItems . length ); // Output : 3
Example 7: Combining Selectors with querySelector
1 <!-- HTML -->
2 <div class =" container ">
3 <p class =" highlight "> Highlighted Text </p>
4 <p> Normal Text </p>
5 </div >
6
7 <!-- JavaScript -->
8 var highlightedText = document . querySelector (". container
. highlight ");
9 console .log( highlightedText . innerHTML ); // Output : Highlighted Text
10 highlightedText .style . fontWeight = "bold ";
3.2 Changing HTML, Styles, and Classes
You can change the content, style, and classes of elements using the DOM.
3.2.1 Changing HTML
Use innerHTML to change the content of an element.
1 <!-- HTML -->
2 <p id=" greetingText ">Hello , student !</p>
3
4 <!-- JavaScript -->
5 document . getElementById (" greetingText "). innerHTML = " Welcome to
Route Academy !";
Example: Updating a Title
1 <!-- HTML -->
2 <h1 id=" pageTitle ">Old Title </h1 >
3
4 <!-- JavaScript -->
6
JavaScript Basics - Route Academy Week 3
5 document . getElementById (" pageTitle "). innerHTML = "New Title for
Week 3";
Example: Adding a List Item
1 <!-- HTML -->
2 <ul id=" taskList ">
3 <li >Task 1</li >
4 </ul >
5
6 <!-- JavaScript -->
7 var list = document . getElementById (" taskList ");
8 list. innerHTML += "<li >Task 2</li >";
3.2.2 Changing Styles
You can change styles using the style property or [Link].
1 <!-- HTML -->
2 <div id =" styleBox "> Styled Box </div >
3
4 <!-- JavaScript -->
5 document . getElementById (" styleBox "). style . backgroundColor = "red ";
6 document . getElementById (" styleBox "). style . width = "500 px ";
7
8 var cssProp = `
9 background -color : blue;
10 width : 200 px;
11 color : white ;
12 `;
13 document . getElementById (" styleBox "). style . cssText = cssProp ;
Example: Changing a Button’s Style
1 <!-- HTML -->
2 <button id=" actionButton "> Click Me!</ button >
3
4 <!-- JavaScript -->
5 document . getElementById (" actionButton ").style . backgroundColor =
"green ";
6 document . getElementById (" actionButton ").style . padding = "10 px ";
Example: Setting a Background Image
1 <!-- HTML -->
2 <div id =" imageBox " style =" width : 200 px; height : 200 px;"> Image
Box </div >
3
4 <!-- JavaScript -->
5 document . getElementById (" imageBox "). style . backgroundImage =
"url('https :// example .com/ image .jpg ') ";
Example: Applying Multiple Styles at Once
7
JavaScript Basics - Route Academy Week 3
1 <!-- HTML -->
2 <p id=" styledText ">Style me!</p>
3
4 <!-- JavaScript -->
5 var cssRules = `
6 border : 1px solid red;
7 padding : 10 px;
8 color : #000;
9 `;
10 document . getElementById (" styledText "). style . cssText = cssRules ;
3.2.3 Managing Classes
Use classList to add, remove, or toggle classes.
1 <!-- HTML -->
2 <div id =" classBox " class =" box"> Class Box </div >
3
4 <!-- JavaScript -->
5 var box = document . getElementById (" classBox ");
6 box. classList .add (" highlight "); // Adds class " highlight "
7 box. classList . remove (" box "); // Removes class "box"
8 box. classList . replace (" highlight ", " active "); // Replaces
" highlight " with " active "
9 box. classList . toggle (" active "); // Toggles " active " on or off
10 console .log(box. classList . contains (" active ")); // Output : false
(after toggle )
Example: Toggling a Dark Mode
1 <!-- HTML -->
2 <div id =" themeBox ">Theme Box </div >
3 <button id=" themeButton "> Toggle Dark Mode </ button >
4
5 <!-- JavaScript -->
6 var themeBox = document . getElementById (" themeBox ");
7 var button = document . getElementById (" themeButton ");
8 button . addEventListener (" click ", function () {
9 themeBox . classList . toggle (" darkMode ");
10 });
Example: Checking for a Class
1 <!-- HTML -->
2 <div id =" checkBox " class =" visible "> Check Me </div >
3
4 <!-- JavaScript -->
5 var checkBox = document . getElementById (" checkBox ");
6 console .log( checkBox . classList . contains (" visible ")); // Output : true
7 checkBox . classList . remove (" visible ");
8 console .log( checkBox . classList . contains (" visible ")); // Output :
false
8
JavaScript Basics - Route Academy Week 3
Example: Replacing Classes on Hover
1 <!-- HTML -->
2 <div id =" hoverBox " class =" normal "> Hover over me!</div >
3
4 <!-- JavaScript -->
5 var hoverBox = document . getElementById (" hoverBox ");
6 hoverBox . addEventListener (" mouseover ", function () {
7 hoverBox . classList . replace (" normal ", " highlighted ");
8 });
9 hoverBox . addEventListener (" mouseout ", function () {
10 hoverBox . classList . replace (" highlighted ", " normal ");
11 });
3.3 Managing Attributes
You can get, set, or remove attributes of elements.
1 <!-- HTML -->
2 <a id=" myLink " href =" https :// example .com">Link </a>
3
4 <!-- JavaScript -->
5 var link = document . getElementById (" myLink ");
6 link. setAttribute (" href", " https :// www. google .com /"); // Change href
7 console .log(link. getAttribute (" href ")); // Output :
https :// www. google .com/
8 console .log(link. hasAttribute (" href ")); // Output : true
9 link. removeAttribute (" href "); // Remove href
10 console .log(link. hasAttribute (" href ")); // Output : false
Example: Changing an Image Source
1 <!-- HTML -->
2 <img id =" myImage " src ="old - image .jpg" alt =" Old Image ">
3
4 <!-- JavaScript -->
5 var image = document . getElementById (" myImage ");
6 image. setAttribute (" src", "new - image .jpg ");
7 image. setAttribute (" alt", "New Image ");
8 console .log(image. getAttribute (" src ")); // Output : new - image .jpg
Example: Adding a Disabled Attribute
1 <!-- HTML -->
2 <button id=" submitButton ">Submit </ button >
3
4 <!-- JavaScript -->
5 var button = document . getElementById (" submitButton ");
6 button . setAttribute (" disabled ", "true ");
7 console .log( button . hasAttribute (" disabled ")); // Output : true
8 button . removeAttribute (" disabled ");
9 console .log( button . hasAttribute (" disabled ")); // Output : false
Example: Checking for a Custom Attribute
9
JavaScript Basics - Route Academy Week 3
1 <!-- HTML -->
2 <div id =" dataBox " data -info =" secret ">Data Box </div >
3
4 <!-- JavaScript -->
5 var dataBox = document . getElementById (" dataBox ");
6 console .log( dataBox . getAttribute (" data -info ")); // Output : secret
7 console .log( dataBox . hasAttribute (" data -info ")); // Output : true
4 Events: Listening to User Actions
Events are like signals that happen when a user does something, like clicking a button or
typing. We can use JavaScript to listen for these events and respond to them.
4.1 Mouse Events
Mouse events happen when the user interacts with the mouse.
• mousedown / mouseup: When a mouse button is pressed or released.
• mouseover / mouseout: When the mouse pointer enters or leaves an element.
• mousemove: When the mouse moves over an element.
• click: When a mouse button is clicked (mousedown then mouseup).
• dblclick: When an element is double-clicked.
• contextmenu: When the right mouse button is clicked (or other context menu
trigger).
1 <!-- HTML -->
2 <div id =" hoverArea " style =" width : 100 px; height : 100 px; background :
lightblue ;"> Hover or click me!</div >
3
4 <!-- JavaScript -->
5 var area = document . getElementById (" hoverArea ");
6 area. addEventListener (" mouseover ", function () {
7 area. style. backgroundColor = " lightgreen ";
8 });
9 area. addEventListener (" mouseout ", function () {
10 area. style. backgroundColor = " lightblue ";
11 });
12 area. addEventListener (" click ", function () {
13 area. innerHTML = " Clicked !";
14 });
Example 1: Double-Click to Change Text
10
JavaScript Basics - Route Academy Week 3
1 <!-- HTML -->
2 <p id=" doubleClickText ">Double - click me!</p>
3
4 <!-- JavaScript -->
5 var text = document . getElementById (" doubleClickText ");
6 text. addEventListener (" dblclick ", function () {
7 text. innerHTML = "You double - clicked !";
8 text. [Link] = " purple ";
9 });
Example 2: Mouse Movement Tracker
1 <!-- HTML -->
2 <div id =" moveBox " style =" width : 200 px; height : 200 px; background :
lightyellow ;"> Move your mouse here !</div >
3
4 <!-- JavaScript -->
5 var moveBox = document . getElementById (" moveBox ");
6 moveBox . addEventListener (" mousemove ", function () {
7 moveBox . innerHTML = " Mouse is moving !";
8 });
9 moveBox . addEventListener (" mouseout ", function () {
10 moveBox . innerHTML = "Move your mouse here !";
11 });
Example 3: Right-Click Menu
1 <!-- HTML -->
2 <div id =" contextBox " style =" width : 150 px; height : 150 px;
background : lightcoral ;">Right - click me!</div >
3
4 <!-- JavaScript -->
5 var contextBox = document . getElementById (" contextBox ");
6 contextBox . addEventListener (" contextmenu ", function ( event ) {
7 event . preventDefault (); // Prevents the default right - click menu
8 contextBox . innerHTML = "Right - clicked !";
9 });
4.2 Keyboard Events
Keyboard events happen when the user presses keys.
• keydown: When a key is pressed down.
• keyup: When a key is released.
1 <!-- HTML -->
2 <input id=" keyInput " type =" text" placeholder =" Type here ..." >
3
4 <!-- JavaScript -->
5 var input = document . getElementById (" keyInput ");
6 input. addEventListener (" keydown ", function () {
11
JavaScript Basics - Route Academy Week 3
7 console .log (" Key pressed !");
8 });
9 input. addEventListener (" keyup ", function () {
10 console .log (" Key released !");
11 });
Example 1: Detecting Specific Keys
1 <!-- HTML -->
2 <input id=" gameInput " type =" text" placeholder =" Press arrow keys ..." >
3
4 <!-- JavaScript -->
5 var gameInput = document . getElementById (" gameInput ");
6 gameInput . addEventListener (" keydown ", function ( event ) {
7 if ([Link] === " ArrowUp ") {
8 console .log (" You pressed the up arrow !");
9 }
10 });
Example 2: Counting Key Presses
1 <!-- HTML -->
2 <input id=" countInput " type =" text" placeholder =" Type to count ..." >
3 <p id=" keyCount ">Key presses : 0</p>
4
5 <!-- JavaScript -->
6 var countInput = document . getElementById (" countInput ");
7 var countDisplay = document . getElementById (" keyCount ");
8 var count = 0;
9 countInput . addEventListener (" keyup ", function () {
10 count ++;
11 countDisplay . innerHTML = "Key presses : " + count ;
12 });
4.3 Input Events
Input events happen when the user changes an input field.
• change: Triggers when the input value changes and the user finishes (e.g., clicks
away).
• input: Triggers every time the input value changes (as the user types).
1 <!-- HTML -->
2 <input id=" textInput " type =" text" placeholder =" Type here ..." >
3 <p id=" textOutput "></p>
4
5 <!-- JavaScript -->
6 var textInput = document . getElementById (" textInput ");
7 var textOutput = document . getElementById (" textOutput ");
8 textInput . addEventListener (" input ", function () {
9 textOutput . innerHTML = "You typed : " + textInput . value ;
12
JavaScript Basics - Route Academy Week 3
10 });
11 textInput . addEventListener (" change ", function () {
12 console .log (" Input changed to: " + textInput . value );
13 });
Example 1: Live Character Counter
1 <!-- HTML -->
2 <input id=" charInput " type =" text" placeholder =" Type to count
characters ..." >
3 <p id=" charCount "> Characters : 0</p>
4
5 <!-- JavaScript -->
6 var charInput = document . getElementById (" charInput ");
7 var charCount = document . getElementById (" charCount ");
8 charInput . addEventListener (" input ", function () {
9 charCount . innerHTML = " Characters : " + charInput . value . length ;
10 });
Example 2: Dropdown Selection Change
1 <!-- HTML -->
2 <select id=" colorSelect ">
3 <option value =" red">Red </ option >
4 <option value =" blue">Blue </ option >
5 <option value =" green ">Green </ option >
6 </select >
7 <div id =" colorBox " style =" width : 100 px; height : 100 px;"></div >
8
9 <!-- JavaScript -->
10 var colorSelect = document . getElementById (" colorSelect ");
11 var colorBox = document . getElementById (" colorBox ");
12 colorSelect . addEventListener (" change ", function () {
13 colorBox . style . backgroundColor = colorSelect . value ;
14 });
13