From 0d30758f7d97bda3ddf9655f52e9a8cb3a27cfd0 Mon Sep 17 00:00:00 2001 From: Mejbaul Mubin <mejbaulmubin@my.uopeople.edu> Date: Sat, 28 Dec 2024 05:28:15 +0600 Subject: [PATCH 1/3] Add advanced DOM manipulation examples: create, append, remove elements; class manipulation; form validation --- README.md | 2873 +++++++++-------- .../14.03.01.js.dom.byid.html | 68 + .../15. DOM (Advanced)/14.03.01.script.js | 31 + .../14.03.02.js.dom.byclass.html | 67 + .../15. DOM (Advanced)/14.03.02.script.js | 26 + .../14.03.03.js.dom.bytag.html | 67 + .../15. DOM (Advanced)/14.03.03.script.js | 34 + .../14.03.04.js.dom.queryselector.html | 68 + .../15. DOM (Advanced)/14.03.04.script.js | 15 + .../14.04.01.js.dom.apply.set.style.html | 70 + .../15. DOM (Advanced)/14.04.01.script.js | 13 + .../14.04.02.js.dom.retreive.get.style.html | 77 + .../15. DOM (Advanced)/14.04.02.script.js | 22 + .../14.04.03.js.dom.css.class.html | 84 + .../15. DOM (Advanced)/14.04.03.script.js | 11 + .../14.04.04.js.dom.css.classlist.html | 86 + .../15. DOM (Advanced)/14.04.04.script.js | 26 + .../14.05.01.js.dom.attribute.apply.set.html | 85 + .../15. DOM (Advanced)/14.05.01.script.js | 18 + ...4.05.02.js.dom.attribute.retreive.get.html | 85 + .../15. DOM (Advanced)/14.05.02.script.js | 19 + .../14.05.03.js.dom.attribute.remove.html | 84 + .../15. DOM (Advanced)/14.05.03.script.js | 22 + 23 files changed, 2681 insertions(+), 1270 deletions(-) create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js diff --git a/README.md b/README.md index 0821454..16dad64 100644 --- a/README.md +++ b/README.md @@ -9,15 +9,13 @@ JavaScript tutorial for Beginners JavaScript basics and fundamentals for all ===================== -Description ---------------------- +## Description JavaScript is a `scripting language of the web` that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.. In this practical course will learn JavaScript basics-programming fundamentals from scratch. We Will start with what is JavaScript? its uses, history, how to write JavaScript, etc. It will also cover various programming building blocks like variable, functions, array, conditionals, objects, and many more. -Topics (separate with spaces) ---------------------- +## Topics (separate with spaces) -Add topics to categorize your repository and make it more discoverable: +Add topics to categorize your repository and make it more discoverable: - javascript-programming-language - javascript-language-fundamentals @@ -40,77 +38,76 @@ Add topics to categorize your repository and make it more discoverable: - vanilla-javascript - javascript-typescript-es6 -Prerequisites for current course / What you need to know ---------------------- +## Prerequisites for current course / What you need to know To move forward with JavaScript you just need basic knowledge of XHTML/HTML. Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge and/or general understanding of: + - The Internet and the World Wide Web (WWW) [Web Design Development Foundations-Web Technology Fundamentals](https://github.com/dinanathsj29/web-design-development-fundamentals) -- Good working knowledge of HyperText Markup Language (HTML) [HTML5 Essentials](https://github.com/dinanathsj29/html5-essentials) and +- Good working knowledge of HyperText Markup Language (HTML) [HTML5 Essentials](https://github.com/dinanathsj29/html5-essentials) and - Its good to know [CSS3 Fundamentals](https://github.com/dinanathsj29/css3-fundamentals) -Topics include -===================== +# Topics include 1. [Course Introduction](#section-01-course-introduction) - - 01.01. [Welcome](#0101-welcome) - - 01.02. [Who is this for? Audience](#0102-who-is-this-for-audience) + - 01.01. [Welcome](#0101-welcome) + - 01.02. [Who is this for? Audience](#0102-who-is-this-for-audience) 2. [Introducing JavaScript](#section-02-introducing-javascript) - - 02.01. [Importance](#0201-importance) - - 02.02. [What is JavaScript?](#0202-what-is-javascript) - - 02.03. [What is a scripting language?](#0203-what-is-a-scripting-language) - - 02.04. [What can you do with JavaScript?](#0204-what-can-you-do-with-javascript) | [Use of JavaScript?](#0204-use-of-javascript) - - 02.05. [Where does the JavaScript code run?](#0205-where-does-the-javascript-code-run) - - 02.06. [Who are using JavaScript?](#0206-who-are-using-javascript) - - 02.07. [History of JavaScript](#0207-history-of-javascript) - - 02.08. [JavaScript Vs ECMAScript](#0208-javascript-vs-ecmascript) - - 02.09. [Types of Script](#0209-types-of-script) | [Various Scripting languages](#0209-various-scripting-languages) | [Client-Side Scripting Vs Server Side Scripting](#0209-client-side-scripting-vs-server-side-scripting) - - 02.10. [Prerequisites of using HTML and JavaScript](#0210-prerequisites-of-using-html-and-javascript) + - 02.01. [Importance](#0201-importance) + - 02.02. [What is JavaScript?](#0202-what-is-javascript) + - 02.03. [What is a scripting language?](#0203-what-is-a-scripting-language) + - 02.04. [What can you do with JavaScript?](#0204-what-can-you-do-with-javascript) | [Use of JavaScript?](#0204-use-of-javascript) + - 02.05. [Where does the JavaScript code run?](#0205-where-does-the-javascript-code-run) + - 02.06. [Who are using JavaScript?](#0206-who-are-using-javascript) + - 02.07. [History of JavaScript](#0207-history-of-javascript) + - 02.08. [JavaScript Vs ECMAScript](#0208-javascript-vs-ecmascript) + - 02.09. [Types of Script](#0209-types-of-script) | [Various Scripting languages](#0209-various-scripting-languages) | [Client-Side Scripting Vs Server Side Scripting](#0209-client-side-scripting-vs-server-side-scripting) + - 02.10. [Prerequisites of using HTML and JavaScript](#0210-prerequisites-of-using-html-and-javascript) 3. [JavaScript Getting Started](#section-03-javascript-getting-started) - - 03.01. [How to write Javascript?](#0301-how-to-write-javascript) | [JavaScript in HTML](#0301-javascript-in-html) - - 03.02. [Where to write JavaScript in HTML?](#0302-where-to-write-javascript-in-html) | [Where to embed include write put JavaScript in HTML?](#0302-where-to-embed-include-write-put-javascript-in-html) - - 03.03. [JavaScript Code structure](#0303-javascript-code-structure) - - 03.04. [JavaScript Keywords](#0304-javascript-keywords) - - 03.05. [Comments](#0305-Comments) + - 03.01. [How to write Javascript?](#0301-how-to-write-javascript) | [JavaScript in HTML](#0301-javascript-in-html) + - 03.02. [Where to write JavaScript in HTML?](#0302-where-to-write-javascript-in-html) | [Where to embed include write put JavaScript in HTML?](#0302-where-to-embed-include-write-put-javascript-in-html) + - 03.03. [JavaScript Code structure](#0303-javascript-code-structure) + - 03.04. [JavaScript Keywords](#0304-javascript-keywords) + - 03.05. [Comments](#0305-Comments) 4. [JavaScript Language Fundamentals](#section-04-javascript-language-fundamentals) - - 04.01. [Generating Output](#0401-generating-output) + - 04.01. [Generating Output](#0401-generating-output) 5. [Variables](#section-05-variables) - - 05.01. [What is Variable?](#0501-what-is-variable) - - 05.02. [Declaring variable without a value](#0502-declaring-variable-without-a-value) | [Creating a variable without a value](#0502-Creating-a-variable-without-a-value) - - 05.03. [Declaring multiple variables at once](#0503-declaring-multiple-variables-at-once) - - 05.04. [Variable Naming Conventions](#0504-variable-naming-conventions) | [Variable Naming Conventions (Identifiers)](#0504-variable-naming-conventions-identifiers) - - 05.05. [Variable Scope](#0505-variable-scope) - - 05.06. [The let and const keywords ES6](#0506-the-let-and-const-keywords-es6) + - 05.01. [What is Variable?](#0501-what-is-variable) + - 05.02. [Declaring variable without a value](#0502-declaring-variable-without-a-value) | [Creating a variable without a value](#0502-Creating-a-variable-without-a-value) + - 05.03. [Declaring multiple variables at once](#0503-declaring-multiple-variables-at-once) + - 05.04. [Variable Naming Conventions](#0504-variable-naming-conventions) | [Variable Naming Conventions (Identifiers)](#0504-variable-naming-conventions-identifiers) + - 05.05. [Variable Scope](#0505-variable-scope) + - 05.06. [The let and const keywords ES6](#0506-the-let-and-const-keywords-es6) 6. [Data types](#section-06-data-types) - - 06.01. [Data types](#0601-data-types) - - 06.02. [Primitive data type](#0602-primitive-data-type) | [Primitive, Primary or Value data type](#0602-primitive-primary-or-value-data-type) - - 06.03. [Non-primitive data type](#0603-non-primitive-data-type) | [Non-primitive, Reference or Composite data type](#0603-non-primitive-reference-or-composite-data-type) - - 06.04. [JavaScript has Dynamic Types](#0604-javascript-has-dynamic-types) - - 06.05. [The typeof Operator](#0605-the-typeof-operator) - - 06.06. [Type conversion](#0606-type-conversion) | [typeof parseInt parseFloat](#0606-typeof-parseint-parsefloat) - - 06.07. [Type coercion](#0607-type-coercion) + - 06.01. [Data types](#0601-data-types) + - 06.02. [Primitive data type](#0602-primitive-data-type) | [Primitive, Primary or Value data type](#0602-primitive-primary-or-value-data-type) + - 06.03. [Non-primitive data type](#0603-non-primitive-data-type) | [Non-primitive, Reference or Composite data type](#0603-non-primitive-reference-or-composite-data-type) + - 06.04. [JavaScript has Dynamic Types](#0604-javascript-has-dynamic-types) + - 06.05. [The typeof Operator](#0605-the-typeof-operator) + - 06.06. [Type conversion](#0606-type-conversion) | [typeof parseInt parseFloat](#0606-typeof-parseint-parsefloat) + - 06.07. [Type coercion](#0607-type-coercion) 7. [Operators](#section-07-operators) - - 07.01. [What is the Operator?](#0701-what-is-the-operator) - - 07.02. [Arithmetic Operators](#0702-arithmetic-operators) - - 07.03. [Assignment Operators](#0703-assignment-operators) - - 07.04. [Logical Operators](#0704-logical-operators) - - 07.05. [Comparison Operators](#0705-comparison-operators) | [Relational Operators](#0705-relational-operators) - - 07.06. [Conditional Operator](#0706-conditional-perator) | [Ternary Operator](#0706-ternary-operator) - - 07.07. [String Operators](#0707-string-operators) - - 07.08. [Operator precedence](#0708-operator-precedence) + - 07.01. [What is the Operator?](#0701-what-is-the-operator) + - 07.02. [Arithmetic Operators](#0702-arithmetic-operators) + - 07.03. [Assignment Operators](#0703-assignment-operators) + - 07.04. [Logical Operators](#0704-logical-operators) + - 07.05. [Comparison Operators](#0705-comparison-operators) | [Relational Operators](#0705-relational-operators) + - 07.06. [Conditional Operator](#0706-conditional-perator) | [Ternary Operator](#0706-ternary-operator) + - 07.07. [String Operators](#0707-string-operators) + - 07.08. [Operator precedence](#0708-operator-precedence) 8. [Functions](#section-08-functions) - - 08.01. [What is a Function?](#0801-what-is-a-function) - - 08.02. [Types of Function](#0802-types-of-function) - - 08.03. [Different ways to define Function](#0803-different-ways-to-define-function) - - 08.04. [String Methods and Concatenation](#0804-string-methods-and-concatenation) - - 08.05. [Template String](#0805-template-string) | [Template Literals](#0805-template-literals) -9. [Loops](#section-09-loops) | [Loops and Iterations](#section-09-loops-and-iterations) - - 09.01. [The for loop](#0901-the-for-loop) - - 09.02. [The while loop](#0902-the-while-loop) - - 09.03. [The do while loop](#0903-the-do-while-loop) - - 09.04. [The for in loop](#0904-the-for-in-loop) - - 09.05. [The for of loop](#0905-the-for-of-loop) - - 09.06. [Break and Continue statement](#0906-break-and-continue-statement) - - 09.07. [for each loop](#0907-for-each-loop) + - 08.01. [What is a Function?](#0801-what-is-a-function) + - 08.02. [Types of Function](#0802-types-of-function) + - 08.03. [Different ways to define Function](#0803-different-ways-to-define-function) + - 08.04. [String Methods and Concatenation](#0804-string-methods-and-concatenation) + - 08.05. [Template String](#0805-template-string) | [Template Literals](#0805-template-literals) +9. [Loops](#section-09-loops) | [Loops and Iterations](#section-09-loops-and-iterations) + - 09.01. [The for loop](#0901-the-for-loop) + - 09.02. [The while loop](#0902-the-while-loop) + - 09.03. [The do while loop](#0903-the-do-while-loop) + - 09.04. [The for in loop](#0904-the-for-in-loop) + - 09.05. [The for of loop](#0905-the-for-of-loop) + - 09.06. [Break and Continue statement](#0906-break-and-continue-statement) + - 09.07. [for each loop](#0907-for-each-loop) 10. [Conditions - Control Flow](#section-10-conditions) - 10.01. [The if statement](#1001-the-if-statement) | [The if statement and comparison operators](#1001-the-if-statement-and-comparison-operators) - 10.02. [The if else statement](#1002-the-if-else-statement) @@ -122,8 +119,8 @@ Topics include - 11.03. [Create Array by creating an instance of array directly](#1103-create-array-by-creating-an-instance-of-array-directly) - 11.04. [Create Array by using an array constructor](#1104-create-array-by-using-an-array-constructor) - 11.05. [Getting the Length of an Array](#1105-getting-the-length-of-an-array) - - 11.06. [Accessing Looping through an Array Elements](#1106-accessing-looping-through-an-array-elements) | - [Loop through an Array Elements](#1106-loop-through-an-array-elements) + - 11.06. [Accessing Looping through an Array Elements](#1106-accessing-looping-through-an-array-elements) | + [Loop through an Array Elements](#1106-loop-through-an-array-elements) - 11.07. [Adding Editing an Array Elements](#1107-adding-editing-an-array-elements) - 11.08. [Removing Deleting an Array Elements](#1108-removing-deleting-an-array-elements) - 11.09. [Array properties and methods](#1109-array-properties-and-methods) @@ -149,86 +146,79 @@ Topics include - 14.03. [JavaScript DOM Selectors](#1403-javascript-dom-selectors) - 14.04. [JavaScript DOM CSS Styling](#1404-javascript-dom-css-styling) - 14.05. [JavaScript DOM HTML get set attributes](#1405-javaScript-dom-html-get-set-attributes) -15. [What's Next Step?](#section-15-whats-next-step) +15. [DOM (Advanced)](#section-15-dom-advanced) + - 15.01. [Dynamic DOM Manipulation](#1501-dynamic-dom-manipulation) + - 15.02. [Class Manipulation](#1502-class-manipulation) + - 15.03. [Handling Forms and Input Fields](#1503-handling-forms-and-input-fields) +16. [What's Next Step?](#section-16-whats-next-step) -Section 01. Course Introduction -===================== +# Section 01. Course Introduction -01.01. Welcome ---------------------- +## 01.01. Welcome Hi All, I'm **`Dinanath Jayaswal, Senior UI/Web Developer and Adobe Certified Expert Professional`**, I wanna welcome you to JavaScript for Beginners. In this course, I will take you through with the ins and outs of learning JavaScript. This course will help you to learn the fundamentals of programming with JavaScript scripting language, from the basics to advanced topics step-by-step. -01.02. Who is this for? Audience ---------------------- +## 01.02. Who is this for? Audience This course is for any Web Designer, Developer who is interested in dynamic Web Design and Development / Web Programming with JavaScript. Anyone who wants to make a career in Web Development or planning on being a front-end developer must learn JavaScript. -Section 02. Introducing JavaScript -===================== +# Section 02. Introducing JavaScript -02.01. Importance ---------------------- +## 02.01. Importance ### 3 pillars / core Languages/Technologies used for Front End Web Design/Development: 1. **HTML (HyperText Markup Language)** - Markup language, Essential Page Structure/Content, Readable and convey structure to a user, Text Layout Model, page Mark-up, Text, Tags, Data, details for pages, Images, Tables, Anchor Links, Forms - - HTML is an acronym stands for `HyperText Markup Language` which is used for creating `web pages and web applications` - - HTML is not a programming language; it is a markup language that defines the structure of your content ie. document + + - HTML is an acronym stands for `HyperText Markup Language` which is used for creating `web pages and web applications` + - HTML is not a programming language; it is a markup language that defines the structure of your content ie. document 2. **CSS (Cascading Style Sheet)** - Style Sheet language, Page Design / Presentation / Layouts / Styling / Formattings, look and feel, Creative part of Web Pages - - CSS is a stylesheet language that allows you to control the appearance (look and feel) of your webpages + + - CSS is a stylesheet language that allows you to control the appearance (look and feel) of your webpages 3. **`JavaScript (JS) - Scripting language, Dynamic Page Behaviour, Logics, Conditions and Validations, Events (mouse click, hover), Interactivity with User, Dynamic updates in a Web Page`** - - JavaScript is a `scripting language of the web` that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc. + - JavaScript is a `scripting language of the web` that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc. > **Syntax & Example**: `02.01.js.intro.html` + ```html <!DOCTYPE html> <html lang="en"> - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>02.01.js.intro.html</title> <!-- internal style --> <style> - /* css selector: { property:value; } */ + /* css selector: { property:value; } */ body { - font-family: arial; + font-family: arial; } </style> <!-- internal JavaScript - head section --> <script> // Write all JavaScript code here - alert('welcome to JavaScript'); - + alert("welcome to JavaScript"); </script> - </head> <body> - Content <!-- internal JavaScript - body section --> <script> - /* Write all JavaScript code here */ - console.log('welcome to JavaScript'); - + /* Write all JavaScript code here */ + console.log("welcome to JavaScript"); </script> - </body> - </html> ``` -02.02. What is JavaScript? ---------------------- +## 02.02. What is JavaScript? - JavaScript is `1 of the 3 core language/layers` of web...(HTML, CSS & JavaScript) - JavaScript is one of the most popular, widely used, lightweight scripting programming language @@ -239,7 +229,7 @@ Section 02. Introducing JavaScript - JavaScript is case sensitive language > **Note**: <br/> -Now-a-days with the help of `Node (Node.js)` JavaScript is used for `Back-end (Server-side)` API development. JavaScript is not compiled language, but it is a translated language (JavaScript Translator (embedded in the browser engine) is responsible for translating the JavaScript code for the web browser. +> Now-a-days with the help of `Node (Node.js)` JavaScript is used for `Back-end (Server-side)` API development. JavaScript is not compiled language, but it is a translated language (JavaScript Translator (embedded in the browser engine) is responsible for translating the JavaScript code for the web browser. <p> <figure> @@ -255,15 +245,14 @@ Now-a-days with the help of `Node (Node.js)` JavaScript is used for `Back-end (S </figure> </p> -02.03. What is a scripting language? ---------------------- +## 02.03. What is a scripting language? - A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages - A programming language designed for integrating and communicating with other programming languages - - Popular scripting languages are `JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP` - - Since a scripting language is normally used in conjunction with another programming language, they are often found and used alongside `HTML, Java or C++` + - Popular scripting languages are `JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP` + - Since a scripting language is normally used in conjunction with another programming language, they are often found and used alongside `HTML, Java or C++` - The simple difference between scripting language and programming language is: Scripting languages do not require the compilation step and are rather interpreted - - `C program` needs to be compiled before running whereas normally, a scripting language like `JavaScript or PHP` need not be compiled + - `C program` needs to be compiled before running whereas normally, a scripting language like `JavaScript or PHP` need not be compiled - Scripting is interpreted based language, whereas Java, C, C++, and others are compiler-based language ### What is a script? @@ -271,12 +260,14 @@ Now-a-days with the help of `Node (Node.js)` JavaScript is used for `Back-end (S - A script is nothing but sets of instructions - Series of commands -02.04. What can you do with JavaScript? ---------------------- -02.04. Use of JavaScript ---------------------- + 02.04. What can you do with JavaScript? + +--- + +## 02.04. Use of JavaScript For a long time, JavaScript is used only as a `Client Side Front End Development language` to build browser-based interactive web pages. But currently due to huge community support `(Node or Nide.js) JavaScript is multi-purpose language` and used to develop: + - Full-fledged Enterprise Web Application - Full-blown Mobile Apps - Real-time Networking Apps (Chats, Audio/Video Streaming Services) @@ -288,7 +279,7 @@ For a long time, JavaScript is used only as a `Client Side Front End Development - JavaScript gives HTML designers a `programming tool` - JavaScript can react to `events` (mouse click, hover (rollover, rollout), focus, blur) - JavaScript can be used to `validate` data (`Client-side validation`) -- JavaScript can manipulate `HTML content` and `CSS styles` +- JavaScript can manipulate `HTML content` and `CSS styles` - Dynamic `drop-down menus`, HTML contents at run time/on the fly - Displaying live/current/dynamic `date and time (clocks)` - Displaying `pop-up windows` and `dialog boxes` (an `alert`, `confirm` and `prompt` dialog box) @@ -302,48 +293,41 @@ For a long time, JavaScript is used only as a `Client Side Front End Development - **Control Browsers** - Opening pages in customized windows - **Validate Forms** - Validating inputs to fields before submitting a form -02.05. Where does the JavaScript code run? ---------------------- + 02.05. Where does the JavaScript code run? + +--- JavaScript was originally designed and developed to run only in browsers. But now with the help of the `Node/Node.js (C++ program, that includes Google's V8 JavaScript engine)` we can build the back-end(server-side) for our web and mobile applications. ### Common JavaScript Browser Engines -| Browser | Engine | -| ---------------------------------------------|-------------------------------------------| -| **Browser, Headless Browser, or Runtime** | **JavaScript Engine** | -| Mozilla | Spidermonkey | -| Safari** | JavaScriptCore* | -| IE and Edge | Chakra | -| Chrome | V8 | -| TrifleJS | V8 | -| Node.js*** | V8 | -| Io.js*** | V8 | -| PhantomJS | JavaScriptCore | -| HTMLUnit | Rhino | -| | | - -02.06. Who are using JavaScript? ---------------------- +| Browser | Engine | +| ----------------------------------------- | --------------------- | +| **Browser, Headless Browser, or Runtime** | **JavaScript Engine** | +| Mozilla | Spidermonkey | +| Safari\*\* | JavaScriptCore\* | +| IE and Edge | Chakra | +| Chrome | V8 | +| TrifleJS | V8 | +| Node.js\*\*\* | V8 | +| Io.js\*\*\* | V8 | +| PhantomJS | JavaScriptCore | +| HTMLUnit | Rhino | +| | | + +## 02.06. Who are using JavaScript? - JavaScript is used by: - - Front-end Developer - - Back-end Developer - - Full-stack Developer - -- Big companies and brands build entire applications: - - Netflix - - Walmart - - PayPal - - Microsoft - - Facebook (React.js) - - Google (Angular.js) - - Ebay - - Uber - - Groupon - -02.07. History of JavaScript ---------------------- + + - Front-end Developer + - Back-end Developer + - Full-stack Developer + +- Big companies and brands build entire applications: - Netflix - Walmart - PayPal - Microsoft - Facebook (React.js) - Google (Angular.js) - Ebay - Uber - Groupon + + 02.07. History of JavaScript + +--- - Invented by `“Brandan Eich”` at `Netscape` in `1995` originally named as `"LiveScript"` - `Netscape` & `Sun Java` agreements to rename `"LiveScript"` to `"JavaScript"` (As `java` is already popular in the market) @@ -351,53 +335,54 @@ JavaScript was originally designed and developed to run only in browsers. But no - `Microsoft` has developed new version of "JavaScript" as `"JScript"` for `IE-3` in `1996` - JavaScript Submitted to `ECMAScript in 1997` -02.08. JavaScript Vs ECMAScript ---------------------- - -| JavaScript | ECMAScript | -| :-------------------------------------------|:--------------------------------------------| -| JavaScript is `scripting programming language` | ECMAScript is a `specification/standard` | -| JavaScript is invented by `Brandan Eich` at `Netscape`| ECMAScript standards defined by `ECMA (European Computer Manufacturers Association)` | -| JavaScript is released in 1995 | First ECMAScript standard published in 1997 | -| JavaScript uses/follows ECMAScript specifications/standards | ECMAScript specification defines many new features for JavaScript | -| | | - -02.09. Types of Script ---------------------- -02.09. Various Scripting languages ---------------------- -02.09. Client-Side Scripting Vs Server Side Scripting ---------------------- - -| Client-Side Scripting | Server-Side Scripting | -| ------------------------------------------|-------------------------------------------| -| Instruction for web Browser | Instruction for web Server | -| Client-side scripting is used when the user's browser already has all the code and the page is altered based on the user's input | Server-side scripting is used to create dynamic pages based several conditions when the user's browser requests the server | -| Response from a client-side script is faster as compared to a server-side script because the scripts are processed on the local computer | Response from a server-side script is slower as compared to a client-side script because the scripts are processed on the remote computer (server) | -| Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browser | Server-side scripting languages such as ASP, PHP, Java, Python, Ruby, etc. run on the webserver and the output sent back to the web browser in HTML format -| **Example**: Javascript, VB script, ActionScript, HTML, XHTML etc. | **Example**: ASP, JSP, PHP, ASP#.Net, Perl, Ruby, Python, CGI etc. -| | | - -02.10. Prerequisites of using HTML and JavaScript ---------------------- + 02.08. JavaScript Vs ECMAScript + +--- + +| JavaScript | ECMAScript | +| :---------------------------------------------------------- | :----------------------------------------------------------------------------------- | +| JavaScript is `scripting programming language` | ECMAScript is a `specification/standard` | +| JavaScript is invented by `Brandan Eich` at `Netscape` | ECMAScript standards defined by `ECMA (European Computer Manufacturers Association)` | +| JavaScript is released in 1995 | First ECMAScript standard published in 1997 | +| JavaScript uses/follows ECMAScript specifications/standards | ECMAScript specification defines many new features for JavaScript | +| | | + +## 02.09. Types of Script + +## 02.09. Various Scripting languages + +## 02.09. Client-Side Scripting Vs Server Side Scripting + +| Client-Side Scripting | Server-Side Scripting | +| ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Instruction for web Browser | Instruction for web Server | +| Client-side scripting is used when the user's browser already has all the code and the page is altered based on the user's input | Server-side scripting is used to create dynamic pages based several conditions when the user's browser requests the server | +| Response from a client-side script is faster as compared to a server-side script because the scripts are processed on the local computer | Response from a server-side script is slower as compared to a client-side script because the scripts are processed on the remote computer (server) | +| Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browser | Server-side scripting languages such as ASP, PHP, Java, Python, Ruby, etc. run on the webserver and the output sent back to the web browser in HTML format | +| **Example**: Javascript, VB script, ActionScript, HTML, XHTML etc. | **Example**: ASP, JSP, PHP, ASP#.Net, Perl, Ruby, Python, CGI etc. | +| | | + +## 02.10. Prerequisites of using HTML and JavaScript ### Tools for building web sites-web pages/writing HTML, CSS & JavaScript 1. **Text Editor/HTML Editor/Code Editor/Visual Code Editor** - `NotePad, NotePad++, SublimeText, Atom, Brackets, Coda, Visual Studio Code, DreamWeaver` etc. - - Just visit registered website of any of your favorite editor, download and install it (like **Visual Studio Code** = https://code.visualstudio.com) - - A JavaScript file (.js) is a text file itself consists of JavaScript code/statements, so to create/modify a JavaScript file we can use any text editors + + - Just visit registered website of any of your favorite editor, download and install it (like **Visual Studio Code** = https://code.visualstudio.com) + - A JavaScript file (.js) is a text file itself consists of JavaScript code/statements, so to create/modify a JavaScript file we can use any text editors 2. **Browsers - To view output of .html pages with .js files** - `Google Chrome, Mozilla Firefox, Internet Explorer, Safari` etc. - - Once the .html/.htm file created and saved, we can create a .js file and link within HTML and then we can see its output in any latest web browser -3. **JavaScript Output / Debugging Tool (Developer console)** - - - alert() or window.alert() - - console.log() - - Google Chrome / Safari – `Developer Tools Inspect` / Inpsect element (in browser -> Right Click on page -> choose `Inspect / Inspect Element -> Console Tab` - - Mozilla FireFox – `Firebug` + - Once the .html/.htm file created and saved, we can create a .js file and link within HTML and then we can see its output in any latest web browser + +3. **JavaScript Output / Debugging Tool (Developer console)** - + - alert() or window.alert() + - console.log() + - Google Chrome / Safari – `Developer Tools Inspect` / Inpsect element (in browser -> Right Click on page -> choose `Inspect / Inspect Element -> Console Tab` + - Mozilla FireFox – `Firebug` -> **Note**: <br/> -Use `F12` key on the keyboard to open the `developer tools` then click on the `Console Tab`, OR on empty area in browser page `Right Click -> Inspect (Developer Tool) -> Console Tab`. Here You can write basic JavaScript statements and/or valid JavaScript code directly in browser console panel/tab and get the output +> **Note**: <br/> +> Use `F12` key on the keyboard to open the `developer tools` then click on the `Console Tab`, OR on empty area in browser page `Right Click -> Inspect (Developer Tool) -> Console Tab`. Here You can write basic JavaScript statements and/or valid JavaScript code directly in browser console panel/tab and get the output <p> <figure> @@ -420,13 +405,11 @@ Use `F12` key on the keyboard to open the `developer tools` then click on the `C </figure> </p> -Section 03. JavaScript Getting Started -===================== +# Section 03. JavaScript Getting Started -03.01. How to write Javascript? ---------------------- -03.01. JavaScript in HTML ---------------------- +## 03.01. How to write Javascript? + +## 03.01. JavaScript in HTML - The HTML `<script>.....</script>` tag is used to embed/insert/implement a JavaScript programs/code into any part of an HTML document/page - The `<script>.....</script>` tag specifies that we are using JavaScript @@ -435,55 +418,52 @@ Section 03. JavaScript Getting Started - So the best practice is to place/add the `<script>.....</script>` at the bottom/end of `body` tag/section ie. just before the closing `</body>` tag > **Note**: <br/> -JavaScript is the default scripting language in HTML. The old HTML standard attributes like `type="text/javascript"` and `language="javascript"` no longer required in modern browser +> JavaScript is the default scripting language in HTML. The old HTML standard attributes like `type="text/javascript"` and `language="javascript"` no longer required in modern browser > **Syntax & Example**: `03.01.js.script.tag.html` + ```html <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>03.01.js.script.tag.html</title> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>03.01.js.script.tag.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - <!-- internal JavaScript - head section --> - <script> - // Write all JavaScript code here - alert('welcome to JavaScript'); - - </script> - + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + <!-- internal JavaScript - head section --> + <script> + // Write all JavaScript code here + alert("welcome to JavaScript"); + </script> </head> <body> - - Content - - <!-- internal JavaScript - body section --> - <script> - /* Write all JavaScript code here */ - console.log('welcome to JavaScript'); - document.write('This is dyanamic content. Hello All, Lets write something on web page'); - - </script> - + Content + + <!-- internal JavaScript - body section --> + <script> + /* Write all JavaScript code here */ + console.log("welcome to JavaScript"); + document.write( + "This is dyanamic content. Hello All, Lets write something on web page" + ); + </script> </body> ``` -03.02. Where to write JavaScript in HTML? ---------------------- -03.02. Where to embed include write put JavaScript in HTML? ---------------------- +## 03.02. Where to write JavaScript in HTML? + +## 03.02. Where to embed include write put JavaScript in HTML? ### JavaScript provides 3 places to write the JavaScript code in our webpage: + 1. Inside the HEAD section 2. Inside the BODY section 3. External JavaScript .js file (separation of concern) @@ -493,17 +473,15 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - JavaScript programs/code/statements can be placed in the `<head>` section of an HTML page - As each `<script>.....</script>` tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in the `head section (<head> element` of the document without any valid reason will significantly impact your website performance -> **Syntax & Example**: `03.02.01.js.head.html` +> **Syntax & Example**: `03.02.01.js.head.html` + ```html <head> - - <!-- internal JavaScript - head section --> - <script> - // Write all JavaScript code here - alert('welcome to JavaScript written in head section'); - - </script> - + <!-- internal JavaScript - head section --> + <script> + // Write all JavaScript code here + alert("welcome to JavaScript written in head section"); + </script> </head> ``` @@ -513,20 +491,18 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - As blocking nature of `<script>.....</script>` tag ideally, scripts should be placed at the end of the `body section`, just before the `closing </body> tag`, it will make your web pages load faster since it prevents obstruction of initial page rendering > **Syntax & Example**: `03.02.02.js.body.html` + ```html <body> - - page content - - <!-- internal JavaScript - body section --> - <script> - // Write all JavaScript code here - alert('welcome to JavaScript written in body section'); - console.log('welcome to JavaScript written in body section'); - document.write('<h2>welcome to JavaScript written in body section</h2>'); - - </script> - + page content + + <!-- internal JavaScript - body section --> + <script> + // Write all JavaScript code here + alert("welcome to JavaScript written in body section"); + console.log("welcome to JavaScript written in body section"); + document.write("<h2>welcome to JavaScript written in body section</h2>"); + </script> </body> ``` @@ -536,11 +512,11 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - We must have to `extract and separate` our JavaScript behavior code from our HTML markup code - A simple thumb-rule is if we have a lot of JavaScript code, we can put it into a separate file - We can use/add/attach an external JavaScript file by using `<script>` tag with `src (source)` attribute: - - ```<script src="path/scriptfile.js"></script>``` - - One can provide a `full URL (absolute path)` or `relative path` from the current page + - `<script src="path/scriptfile.js"></script>` + - One can provide a `full URL (absolute path)` or `relative path` from the current page - We can create a single external JavaScript file and embed it in many/any HTML page which provide `code re-usability` -### 03.02.04. Advantages of External JavaScript +### 03.02.04. Advantages of External JavaScript - It separates HTML and JavaScript code (separation of concern) - Code re-usability @@ -548,32 +524,32 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - Web page loads faster /increase the speed of the webpage (Cached JavaScript files) > **Note**: <br/> -Usually, when an external JavaScript file is downloaded for the first time, it is stored in the browser's cache (like images and style sheets), so it won't need to be get downloaded multiple times from the web server that makes the web pages load faster/quickly. +> Usually, when an external JavaScript file is downloaded for the first time, it is stored in the browser's cache (like images and style sheets), so it won't need to be get downloaded multiple times from the web server that makes the web pages load faster/quickly. > **Syntax & Example - `.html file`**: `03.02.03.js.external.html` + ```html <body> + page content - page content - - <!-- include external JavaScript - body section --> - <script src="./03.script.js"></script> - + <!-- include external JavaScript - body section --> + <script src="./03.script.js"></script> </body> ``` > **Syntax & Example - `.js file`**: `03.02.03.script.js` + ```javascript // external js file // Write all JavaScript code here -alert('welcome to JavaScript written in external file'); -console.log('welcome to JavaScript written in external file'); -document.write('<h2>welcome to JavaScript written in external file</h2>'); +alert("welcome to JavaScript written in external file"); +console.log("welcome to JavaScript written in external file"); +document.write("<h2>welcome to JavaScript written in external file</h2>"); ``` -03.03. JavaScript Code structure ---------------------- +## 03.03. JavaScript Code structure + The syntax of JavaScript is the `set of rules` that define a correctly structured JavaScript program. Let's study some of the building blocks of JavaScript code: ### 03.03.01. JavaScript Statements @@ -587,10 +563,10 @@ The syntax of JavaScript is the `set of rules` that define a correctly structure - JavaScript ignores extra line breaks and white spaces - JavaScript is case sensitive language (VB, Pascal, HTML are case insensitive) - JavaScript is interpreted not compiled (write and handed over to the web browser) -- All statement in JavaScript should be terminated by a `Semicolon;` +- All statement in JavaScript should be terminated by a `Semicolon;` > **Note**: <br/> -JavaScript statements are composed of: **`Values, Operators, Expressions, Keywords, and Comments`** +> JavaScript statements are composed of: **`Values, Operators, Expressions, Keywords, and Comments`** ### 03.03.02. Whitespace and Line Breaks @@ -605,7 +581,7 @@ JavaScript statements are composed of: **`Values, Operators, Expressions, Keywor - **In most cases, a newline implies a semicolon, But “in most cases” does not mean “always”!** > **Note**: <br/> -It is a good programming practice to use semicolons; after every statement +> It is a good programming practice to use semicolons; after every statement ### 03.03.04. Case Sensitivity @@ -614,7 +590,7 @@ It is a good programming practice to use semicolons; after every statement - **Example**: `var firstName='Dinanath';` and `var FirstName='Dinanath';` here `firstName & FirstName` are different ie. two different variable > **Note**: <br/> -Take care/precautions while writing variable and function names in JavaScript +> Take care/precautions while writing variable and function names in JavaScript ### 03.03.05. JavaScript Code Blocks @@ -624,13 +600,14 @@ Take care/precautions while writing variable and function names in JavaScript - An often occurrence of a code block in JavaScript is a JavaScript `function` > **Syntax & Example**: `03.03.05.script.js` + ```javascript // external js file // Write all JavaScript code here // define function - block of code to show welcome message function sayHello() { - alert('Hello All! Welcome to JavaScript!!'); + alert("Hello All! Welcome to JavaScript!!"); } // define function - block of code to show total of two numbers @@ -638,7 +615,7 @@ function showTotal() { var num1 = 10; var num2 = 20; var total = num1 + num2; - alert('Total is : ' + total); + alert("Total is : " + total); } // invoke / run / call a function @@ -646,25 +623,27 @@ sayHello(); showTotal(); ``` -03.04. JavaScript Keywords ---------------------- +## 03.04. JavaScript Keywords Usually, JavaScript commands/statements start with a `specific keyword` which defines what `action/function` should the browser will perform/do: -| Keyword | Keyword |Keyword | Keyword |Keyword | -| ------------------|------------------|------------------|------------------|------------------| -| break | do ... while | if ... else | try ... catch | const | -| continue | for | return | var | class | -| debugger | function | switch | let | import | -| | | | | | +| Keyword | Keyword | Keyword | Keyword | Keyword | +| -------- | ------------ | ----------- | ------------- | ------- | +| break | do ... while | if ... else | try ... catch | const | +| continue | for | return | var | class | +| debugger | function | switch | let | import | +| | | | | | ### 03.04.01. Reserved Keywords JavaScript has several reserved keywords. These are the words that you cannot use as identifiers (variable names, function names, and loop labels) in your JavaScript programs. The following list shows the keywords that are reserved in `ECMAScript 6`. It also includes keywords that are `reserved for future` as well as keywords that are `disallowed in strict mode`. -- arguments, await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield, -03.05. Comments ---------------------- +- arguments, await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield, + + 03.05. Comments + +--- + - The comments are a meaningful way to `deliver the message (description to code)` for others/for future reference and to understand/follow the code statements/lines - Comments are special lines written for other developers as a reference purpose and browser ignores while interpreting - It is used to add information about the code, warnings or suggestions so that end-user can easily interpret the code (`Why and How of code/program/logic`) @@ -677,6 +656,7 @@ JavaScript has several reserved keywords. These are the words that you cannot us ### 03.05.01. Types of JavaScript Comments There are two types of comments in JavaScript: + 1. Single-line Comments 2. Multi-line Comments @@ -688,15 +668,16 @@ There are two types of comments in JavaScript: - Single-line comments do not need closure/closing > **Syntax & Example**: `03.05.script.js` + ```javascript // external js file // Write all JavaScript code here // show alert box -alert('Welcome to JavaScript!'); +alert("Welcome to JavaScript!"); -var firstName = 'Dinanath'; // variable to store firstName -var lastName = 'Jayaswal'; // variable to store lastName +var firstName = "Dinanath"; // variable to store firstName +var lastName = "Jayaswal"; // variable to store lastName ``` #### 03.05.01.02. Multi-line Comments @@ -704,14 +685,15 @@ var lastName = 'Jayaswal'; // variable to store lastName - Multi-line comments usually comment out a block of code - Multi-line comments in JavaScript can comment on bigger parts (a few lines) of code - Multi-line comments are more convenient as it can be used to comment single as well as multi-line comments -- Multiline comments start with `forward slash and an asterisk, /* and also end with an asterisk and a forward slash */`: /* multi-line comment */ +- Multiline comments start with `forward slash and an asterisk, /* and also end with an asterisk and a forward slash */`: /_ multi-line comment _/ - Multi-line comments need closing - Multi-line comments are more often used for `formal documentation` -> **Syntax & Example**: `03.05.script.js` +> **Syntax & Example**: `03.05.script.js` + ```javascript /* show alert box */ -alert('Welcome to JavaScript!'); +alert("Welcome to JavaScript!"); /* This is a multiline comment. A code block can be commented on. */ @@ -720,11 +702,10 @@ A code block can be commented on. */ var lastName = 'Jayaswal'; // variable to store lastName */ ``` -Section 04. JavaScript Language Fundamentals -===================== +# Section 04. JavaScript Language Fundamentals + +## 04.01. Generating Output -04.01. Generating Output ---------------------- - JavaScript does not have any `display or built-in print` functions - Many times we may need to generate output from your JavaScript code like `see the value of a variable`, or `write a message to browser console` to help you `debug an issue` in your running JavaScript code, and so on - That is why you have to use the JavaScript output function to generating output `(browser window or browser console dialog boxes, writing output into an HTML element, etc.)` @@ -734,22 +715,24 @@ Section 04. JavaScript Language Fundamentals 1. Writing into an alert box with `alert() or window.alert()` 2. Writing into browser console with `console.log()` -3. Writing into the HTML / Browser Window with `document.write()` +3. Writing into the HTML / Browser Window with `document.write()` 4. Write into an element of HTML / Inserting Output Inside an HTML Element with `innerHTML` #### 04.01.01. Displaying Output in Alert Dialog Boxes: alert() or window.alert() -- One can use `alert dialog boxes` to display the message or output data to the user + +- One can use `alert dialog boxes` to display the message or output data to the user - An alert dialog box is created using the `alert() or window.alert()` method - A small pop-up box appears with a closing button to close alert-box - This method is great for short and rapid informative messages which can be instantly closed > **Syntax & Example**: `04.01.01.script.js` + ```javascript // external js file // Write all JavaScript code here -alert('I am Dinanath Jayaswal'); -window.alert('We are learning JavaScript'); +alert("I am Dinanath Jayaswal"); +window.alert("We are learning JavaScript"); ``` #### 04.01.02. Writing Output to Browser Console: console.log() @@ -759,16 +742,17 @@ window.alert('We are learning JavaScript'); - This is a simple, easy but very powerful method for generating detailed output > **Syntax & Example**: `04.01.02.script.js` + ```javascript // external js file // Write all JavaScript code here -console.log('I am Dinanath Jayaswal'); -console.log('We are learning JavaScript'); +console.log("I am Dinanath Jayaswal"); +console.log("We are learning JavaScript"); ``` > **Note**: <br/> -Use `F12` key on the keyboard to open the `developer tools` then click on the `console tab`. You can write basic JavaScript statements directly in the browser console panel/tab and get the output. +> Use `F12` key on the keyboard to open the `developer tools` then click on the `console tab`. You can write basic JavaScript statements directly in the browser console panel/tab and get the output. #### 04.01.03. Writing Output into the HTML / Browser Window: document.write() @@ -776,50 +760,52 @@ Use `F12` key on the keyboard to open the `developer tools` then click on the `c - Programmers do ues document.write() for `testing purposes` > **Syntax & Example**: `04.01.03.script.js` + ```javascript // external js file // Write all JavaScript code here -document.write('I am Dinanath Jayaswal'); -document.write('We are learning JavaScript'); +document.write("I am Dinanath Jayaswal"); +document.write("We are learning JavaScript"); ``` #### 04.01.04. Inserting Output Inside an HTML Element: innerHTML - We can write or insert output inside an HTML element using the element's `innerHTML` property -- First we need to select the element using a method such as `document.getElementById(id)` +- First we need to select the element using a method such as `document.getElementById(id)` > **Note**: <br/> -HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts +> HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts > **Syntax & Example**: `04.01.04.script.js` + ```javascript /// external js file // Write all JavaScript code here // Writing text string inside an element -document.getElementById('mainHeadingText').innerHTML = 'Heading Text change dynamically on run-time'; +document.getElementById("mainHeadingText").innerHTML = + "Heading Text change dynamically on run-time"; -var paraText = document.getElementById('mainParaText'); -paraText.innerHTML = '<strong>This Paragraphic text inserted dynamically through innerHTML method.</strong>'; +var paraText = document.getElementById("mainParaText"); +paraText.innerHTML = + "<strong>This Paragraphic text inserted dynamically through innerHTML method.</strong>"; ``` With JavaScript, we can do many cool and dynamic pieces of stuff (Image Gallery, Games, Forms) but for that one should be familiar with core essentials/building blocks of JavaScript programming language like Variables, Functions, Operators, Loops, Conditional Statements, Array, Objects, Events, DOM (Document Object Model), etc. which will cover in coming lessons. -Section 05. Variables -===================== +# Section 05. Variables -05.01. What is Variable? ---------------------- +## 05.01. What is Variable? Variables are one of the most fundamental concepts in JavaScript and other all programming languages of the world. - A variable is `container to store/hold the data/information` -- Developers/Programmers use Variable to `store/hold the data/information temporarily` in computer memory +- Developers/Programmers use Variable to `store/hold the data/information temporarily` in computer memory - A variable is a kind of data holder where we can store some value for programming or calculation purpose - A JavaScript variable is simply a `name of the storage location (named containers/named storage)` for data -- Variables are symbolic names for values -- Variables are used to store data of different types like a string of text, numbers, boolean values like true/false, an array of data, etc. +- Variables are symbolic names for values +- Variables are used to store data of different types like a string of text, numbers, boolean values like true/false, an array of data, etc. - The data or value stored in the variables can be set, updated, and retrieved whenever needed - Variables are declared using the keyword `var` keyword - The `assignment operator (=)` is used to assign value to a variable, like this: `var varName = value;` or `var firstName = 'JavaScript';` @@ -833,31 +819,32 @@ Variables are one of the most fundamental concepts in JavaScript and other all p <hr/> > **Note**: <br/> -In ES6 `'let'` and `'const'` keywords are used to defined variables +> In ES6 `'let'` and `'const'` keywords are used to defined variables > **Note**: <br/> -As a best practice of ES6, from now onwards variables must be define with `let` keyword: `let techName = 'JavaScript' ; ` +> As a best practice of ES6, from now onwards variables must be define with `let` keyword: `let techName = 'JavaScript' ; ` <hr/> > **Syntax & Example**: `05.01.script.js` + ```javascript // variables defined to hold different types of data -var techName = 'JavaScript'; // String literal +var techName = "JavaScript"; // String literal var version = 6; // Number literal var isDone = true; // Boolean literal -console.log('Learning '+techName+version); +console.log("Learning " + techName + version); ``` -05.02. Declaring variable without a value ---------------------- -05.02. Creating a variable without a value ---------------------- +## 05.02. Declaring variable without a value + +## 05.02. Creating a variable without a value Variables can also be declared without having any initial values assigned to them. This is useful for variables that are supposed to hold values like user inputs, calculations, status updates, etc. > **Syntax & Example**: `05.01.script.js` + ```javascript // Declaring Variables var techName; @@ -865,11 +852,11 @@ var version; var isDone; // Assigning value -techName = 'JavaScript'; +techName = "JavaScript"; version = 6; isDone = true; -console.log('Learning '+techName+version); +console.log("Learning " + techName + version); // ------------------------------ @@ -877,32 +864,37 @@ console.log('Learning '+techName+version); var userName; // Assigning value -userName = 'Dinanath'; +userName = "Dinanath"; -console.log('Welcome '+userName); +console.log("Welcome " + userName); ``` -05.03. Declaring multiple variables at once ---------------------- +## 05.03. Declaring multiple variables at once We can also `declare multiple variables` and set their initial values in a single statement, each variable is `separated by comma`. > **Syntax & Example**: `05.01.script.js` + ```javascript // Declaring multiple variables -var techName = 'JavaScript', version = 6, isDone = true; +var techName = "JavaScript", + version = 6, + isDone = true; // Declaring multiple variables in multiple lines for readability -var techName = 'JavaScript', -version = 6, -isDone = true; +var techName = "JavaScript", + version = 6, + isDone = true; -console.log('Learning '+techName+version); +console.log("Learning " + techName + version); // ------------------------------ // Declaring multiple variables -var firstName = 'Dinanath', lastName = 'Jayaswal', age = 35, isMarried = 'true'; +var firstName = "Dinanath", + lastName = "Jayaswal", + age = 35, + isMarried = "true"; // Declaring multiple variables in multiple lines for readability /* var firstName = 'Dinanath', @@ -910,15 +902,14 @@ lastName = 'Jayaswal', age = 35, isMarried = 'true'; */ -console.log('I am ' + firstName + ' ' + lastName); +console.log("I am " + firstName + " " + lastName); ``` -05.04. Variable Naming Conventions ---------------------- -05.04. Variable Naming Conventions (Identifiers) ---------------------- +## 05.04. Variable Naming Conventions -All JavaScript variables must be `identified`/referred/defined/named with `unique names`, called as `identifiers`. The naming rules in JavaScript are not much different from any other programming language. +## 05.04. Variable Naming Conventions (Identifiers) + +All JavaScript variables must be `identified`/referred/defined/named with `unique names`, called as `identifiers`. The naming rules in JavaScript are not much different from any other programming language. - There are some rules while declaring/naming a JavaScript variable (also known as `identifiers`) - Identifiers are `simply names` in JavaScript @@ -928,9 +919,9 @@ All JavaScript variables must be `identified`/referred/defined/named with `uniqu **The basic rules for defining/assigning names for variables (unique identifiers) are:** - A variable name must `start with a letter, underscore (_), or dollar sign ($)` - - **Example**: var firstName, var _firstName, var $firstName; + - **Example**: var firstName, var \_firstName, var $firstName; - Names can contain letters, digits, underscores, and dollar signs - - **Example**: var $num_total1; + - **Example**: var $num_total1; - A variable name `cannot start with a number or special characters` - **Example**: var 1num_total, var .num_total - A variable name `cannot contain spaces` @@ -938,33 +929,36 @@ All JavaScript variables must be `identified`/referred/defined/named with `uniqu - A variable Names are `case sensitive` - **Example**: var firstName='Dinanath'; and var FirstName='Dinanath'; here `firstName & FirstName` are different ie. two different variable - A variable name cannot be a `JavaScript keyword or a JavaScript reserved word` - - **Example**: var var; var switch; var for; var true; + - **Example**: var var; var switch; var for; var true; - One should Always give `meaningful/descriptive names` to variables - for naming the variables that contain multiple words, `camelCase` method is commonly used (camelCase is the default method for identifier naming) > **Note**: <br/> -In the programming world, there have been two most popular methods/mechanism of writing multiple words identifiers: (Underscore, Camel Case) +> In the programming world, there have been two most popular methods/mechanism of writing multiple words identifiers: (Underscore, Camel Case) 1. **Underscore**: first_name, last_name, date_of_birth, is_passed, native_place -2. **Camel Case:**: firstName, lastName, dateOfBirth, isPassed, nativePlace OR <br/> : FirstName, LastName, DateOfBirth, IsPassed, NativePlace +2. **Camel Case:**: firstName, lastName, dateOfBirth, isPassed, nativePlace OR <br/> : FirstName, LastName, DateOfBirth, IsPassed, NativePlace > **Syntax & Example**: `05.04.script.js` + ```javascript // variables defined to hold different types of data -var _firstName = 'JavaScript'; +var _firstName = "JavaScript"; var $version = 6; var $num_total1 = 10; -window.alert('variables details: ' + _firstName + ' ' + $version + ' ' + $num_total1); +window.alert( + "variables details: " + _firstName + " " + $version + " " + $num_total1 +); // wrong identifiers // var #name; ``` -05.05. Variable Scope ---------------------- +## 05.05. Variable Scope The scope of a variable is the region/coverage of your program in which it is defined and exist/available. JavaScript variables have two scopes: + 1. Local Variables 2. Global Variables @@ -976,18 +970,19 @@ The scope of a variable is the region/coverage of your program in which it is de - `Function parameters` are always local to that function > **Note**: <br/> -In the function body, a `local variable takes precedence` over a global variable with the same name. +> In the function body, a `local variable takes precedence` over a global variable with the same name. > **Syntax & Example**: `05.05.01.script.js` + ```javascript // global variable -var globalName = 'Global'; +var globalName = "Global"; window.alert(globalName); function showName() { // local variable - var localName = 'Local'; + var localName = "Local"; window.alert(localName); window.alert(globalName); // recall global variable @@ -1002,80 +997,84 @@ window.alert(localName); #### 05.05.02. Global Variables -- A variable `declared outside the function/at the root` or declared `with window object` is known as a global variable -- A JavaScript global variable is accessible from any function +- A variable `declared outside the function/at the root` or declared `with window object` is known as a global variable +- A JavaScript global variable is accessible from any function - A global variable has a global scope which means it can be defined and accessible anywhere in JavaScript code/program > **Syntax & Example**: `05.05.02.script.js` + ```javascript // global variable -var globalName = 'Global'; +var globalName = "Global"; window.alert(globalName); function showName() { // local variable - var globalName = 'Local'; + var globalName = "Local"; window.alert(globalName); // define global variable with window window.globalVersion = 29; - window.alert('global variable from inside function: ' + window.globalVersion); + window.alert("global variable from inside function: " + window.globalVersion); } // invoke/call/run function showName(); // access global variable defined inside function -window.alert('global variable from outside function: ' + window.globalVersion); +window.alert("global variable from outside function: " + window.globalVersion); ``` -05.06. The let and const keywords ES6 ---------------------- +## 05.06. The let and const keywords ES6 + ES6 introduces two new keywords `let` and `const` for declaring variables. The `var, let and const` keywords are almost the same, just a few differences with the scope. -- In older programs` var` is used a lot which declares a variable `(function-scoped variables)`, but in a slightly different `old` way, with scope issues -- Both `let` and `const` keywords declare variables, `scoped at block-level ({})` +- In older programs` var` is used a lot which declares a variable `(function-scoped variables)`, but in a slightly different `old` way, with scope issues +- Both `let` and `const` keywords declare variables, `scoped at block-level ({})` - Block scoping means that a new scope is created `between a pair of curly brackets {}` ### 05.06.01. The let Keyword `ES6` introduces the new `let` keyword for declaring variables. Prior to ES6, the only way to declare a variable in JavaScript was the var keyword. Let's see what's the difference: + - Variables declared with the `var` keyword are `function-scoped` and can be `hoisted` at the top within its scope - Variables declared with `let` keyword are `block-scoped ({})` and they are not hoisted > **Syntax & Example**: `05.06.01.script.js` + ```javascript // traditional var syntax -var techName1 = 'JavaScript'; +var techName1 = "JavaScript"; -for(var i = 1; i <= 5; i++) { - console.log('i : ' + i); // 1,2,3,4,5 - console.log('inside block:' + techName1); +for (var i = 1; i <= 5; i++) { + console.log("i : " + i); // 1,2,3,4,5 + console.log("inside block:" + techName1); var version1 = 100; } -console.log('outside: ' + i); -console.log('outside: ' + version1); +console.log("outside: " + i); +console.log("outside: " + version1); // ------------------------------ // ES6 syntax -let techName2 = 'LiveScript'; +let techName2 = "LiveScript"; -for(let n = 1; n <= 5; n++) { - console.log('n : ' + n); // 1,2,3,4,5 - console.log('inside block:' + techName2); +for (let n = 1; n <= 5; n++) { + console.log("n : " + n); // 1,2,3,4,5 + console.log("inside block:" + techName2); let version2 = 100; } console.log(n); // undefined -console.log('outside: ' + version2); // undefined +console.log("outside: " + version2); // undefined ``` ### 05.06.02. The const Keyword -`ES6` introduces the new `const` keyword for declaring variables. +`ES6` introduces the new `const` keyword for declaring variables. + - Use `const` to declare a constant `(read-only / unchanging)` variable - Constants are `read-only`, you `cannot reassign new values` to them - In Programm/logic when the variable will never change, they can be declared as `const` @@ -1084,6 +1083,7 @@ console.log('outside: ' + version2); // undefined - However, you can change `object properties` or `array elements` > **Syntax & Example**: `05.06.02.script.js` + ```javascript // traditional var syntax var PI1 = 3.14; @@ -1096,47 +1096,44 @@ console.log(PI1); // 100 // ES6 syntax const PI2 = 6.28; -console.log('ES6 syntax const: ' + PI2); // 6.28 +console.log("ES6 syntax const: " + PI2); // 6.28 PI2 = 100; // error ``` -Section 06. Data types -===================== +# Section 06. Data types -06.01. Data types ---------------------- +## 06.01. Data types A variable in JavaScript can contain `any type of data`. Data types specify what `kind of data` can be stored and manipulated within the variable in a program. In JavaScript, different data types are available to hold different types of values/data. There are `two main categories/types` of data types in JavaScript: + 1. Primitive (Primary or Value) data type - - String - - Number - - Boolean - - Undefined - - Null - - Symbol (newly introduced in ES6) -2. Non-primitive (Reference or Composite) data type - - Array - - Object - - Function - -06.02. Primitive data type ---------------------- -06.02. Primitive, Primary or Value data type ---------------------- + - String + - Number + - Boolean + - Undefined + - Null + - Symbol (newly introduced in ES6) +2. Non-primitive (Reference or Composite) data type - Array - Object - Function + + 06.02. Primitive data type + +--- + +## 06.02. Primitive, Primary or Value data type Primitive data types can `hold only one value at a time`. Primitives are `compared by value`. Two values are strictly equal if they have the same value. There are different types of primitive data types in JavaScript. They are as follows: -| Data Type | Description | -| ----------------|-----------------------------------------------------------------------------| -| String | represent textual data. e.g. "welcome" or 'to javascript' | -| Number | represents numeric values e.g. 10, 100.29 | -| Boolean | represents boolean value either false or true | -| Undefined | represents an undefined value (a variable declared but value not assigned) | -| Null | represents null i.e. no value at all | -| | | +| Data Type | Description | +| --------- | -------------------------------------------------------------------------- | +| String | represent textual data. e.g. "welcome" or 'to javascript' | +| Number | represents numeric values e.g. 10, 100.29 | +| Boolean | represents boolean value either false or true | +| Undefined | represents an undefined value (a variable declared but value not assigned) | +| Null | represents null i.e. no value at all | +| | | ### 06.02.01. String @@ -1146,18 +1143,18 @@ There are different types of primitive data types in JavaScript. They are as fol - **Example**: `06.02.script.js` ```js -var firstName = "Java"; -var lastName = 'Script'; +var firstName = "Java"; +var lastName = "Script"; ``` ### 06.02.02. Number - The number data type simply defined without quotes is used to represent positive or negative numbers with or without a decimal place - Many mathematical operations can be done on numbers, e.g. `multiplication *, division /, addition +, subtraction`, and so on -- **Example**: +- **Example**: ```js -var age = 25; +var age = 25; var id = 1; ``` @@ -1166,10 +1163,10 @@ var id = 1; - The Boolean data type can hold only two values: `true or false` - true = ON / yes / correct / 1, false = OFF / no, incorrect / 0 - Boolean data types is often used in `conditional testing` of code -- **Example**: +- **Example**: ```js -var isDone = true; +var isDone = true; var isMarried = false; ``` @@ -1179,7 +1176,7 @@ var isMarried = false; - The undefined data type can only have one value-the special value undefined - A Variable has been declared, but `not assigned a value` - A variable `without a value`, The type is also undefined -- **Example**: +- **Example**: ```js var firstName; @@ -1191,17 +1188,16 @@ var country; - A null value means that there is no value - The special value which represents `“ nothing”, “empty” or “value unknown”` - It is not equivalent to an empty string ('' or ' ', "", " "), it is simply nothing -- **Example**: +- **Example**: ```js var firstName = null; var id = null; ``` -06.03. Non-primitive data type ---------------------- -06.03. Non-primitive, Reference or Composite data type ---------------------- +## 06.03. Non-primitive data type + +## 06.03. Non-primitive, Reference or Composite data type - Non-primitive/Reference data types can hold `collections of values and more complex entities` - Non-primitive values are being compared by `reference` instead of value @@ -1210,38 +1206,38 @@ var id = null; There are different types of non-primitive data types in JavaScript. They are as follows: -| Data Type | Description | -| ----------------|-----------------------------------------------------------------------| -| Array | represents a group of similar value (multiple values in one variable) | -| Object | represents an instance through which we can access members (property & value) | -| Function | represents function (bunch/block of line to execute once) | -| | | +| Data Type | Description | +| --------- | ----------------------------------------------------------------------------- | +| Array | represents a group of similar value (multiple values in one variable) | +| Object | represents an instance through which we can access members (property & value) | +| Function | represents function (bunch/block of line to execute once) | +| | | -06.04. JavaScript has Dynamic Types ---------------------- +## 06.04. JavaScript has Dynamic Types We have two types of programming languages: + 1. Static languages - - Declare a variable, the type of the variable is set and it cannot be changed in the future + - Declare a variable, the type of the variable is set and it cannot be changed in the future 2. Dynamic languages - - Variable can change at run time (one variable can store different types of value as per requirement, we again assign any value any time as per logic, requirements) + - Variable can change at run time (one variable can store different types of value as per requirement, we again assign any value any time as per logic, requirements) -- A JavaScript `variable can contain/hold any data ie. any type of data`, A variable at one moment can be a number and at another moment be a string, boolean +- A JavaScript `variable can contain/hold any data ie. any type of data`, A variable at one moment can be a number and at another moment be a string, boolean - It simply means that `same variable can be used to hold different data types` - JavaScript is a dynamic type language, means you don't need to specify a type of the variable because it is dynamically used by JavaScript engine > **Syntax & Example**: `06.04.script.js` + ```javascript -let name = 'JavaScript'; +let name = "JavaScript"; name = false; name = 100; alert(name); -alert(typeof(name)); +alert(typeof name); ``` -06.05. The typeof Operator ---------------------- +## 06.05. The typeof Operator - The typeof operator returns the `type of the argument` - It’s useful to process values of different types differently or want to perform a quick data type check @@ -1249,44 +1245,45 @@ alert(typeof(name)); - It can be used with or without parentheses `(typeof(x)` or `typeof x` > **Syntax & Example**: `06.05.script.js` + ```javascript // use typeof to find data type of variables // Strings alert(typeof "Hello"); // "string" -alert(typeof '12'); // "string" +alert(typeof "12"); // "string" // Numbers -console.log(typeof(100)); // "number" -console.log(typeof(100.29)); // "number" +console.log(typeof 100); // "number" +console.log(typeof 100.29); // "number" // Booleans alert(typeof true); // "boolean" -alert(typeof(1 == 2)); // "boolean" +alert(typeof (1 == 2)); // "boolean" // Undefined console.log(typeof undefined); // "undefined" var init; -console.log('type of init: ' + typeof init); // "undefined" +console.log("type of init: " + typeof init); // "undefined" // Null console.log(typeof null); // "object" var initObject = null; -console.log('type of initObject: ' + typeof initObject); // "object" +console.log("type of initObject: " + typeof initObject); // "object" // Objects -alert(typeof {name: 'Dinanath', age: 35}); // "object" +alert(typeof { name: "Dinanath", age: 35 }); // "object" alert(typeof document); // "object" alert(typeof window); // "object" // Arrays var techArray = []; -console.log('type of techArray: ' + typeof techArray); // "object" -console.log(typeof ['JavaScript', 'jQuery', 'Angular']); // "object" -console.log(typeof ['Dinanath', 35, 'India']); // "object" +console.log("type of techArray: " + typeof techArray); // "object" +console.log(typeof ["JavaScript", "jQuery", "Angular"]); // "object" +console.log(typeof ["Dinanath", 35, "India"]); // "object" // Functions -console.log(typeof function(){}); // "function" +console.log(typeof function () {}); // "function" console.log(typeof alert); // "function" console.log(typeof window.alert); // "function" @@ -1294,16 +1291,16 @@ console.log(typeof window.alert); // "function" alert(typeof Symbol("dob")); // "symbol" ``` -06.06. Type conversion ---------------------- -06.06. typeof parseInt parseFloat ---------------------- +## 06.06. Type conversion + +## 06.06. typeof parseInt parseFloat - Type conversion is nothing but taking a variable and changing its data type as per needs requirements and logic - In JavaScript as and when we take an `input in the form, its data type is a string by default`, so do any calculations we need to `parse` to `integer/int or the number` - Data type conversion can be either implicit (automatic) or explicit (forcefully/manually) -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // Number to String conversion let num1 = 100; @@ -1331,18 +1328,18 @@ console.log(curDate); console.log(typeof curDate); // Array to String conversion -let numArray = String([1,2,3,4,5]); +let numArray = String([1, 2, 3, 4, 5]); console.log(numArray); console.log(typeof numArray); // toString() method -let curString = (1000).toString -let curString = (true).toString +let curString = (1000).toString; +let curString = true.toString; // String to Number conversion -let num2 = '100'; +let num2 = "100"; console.log(num2); console.log(typeof num2); @@ -1359,55 +1356,57 @@ let boolValue2 = Number(false); // parseInt() method -let curNumber = parseInt('100'); -let curNumber = parseFloat('100.41'); +let curNumber = parseInt("100"); +let curNumber = parseFloat("100.41"); ``` -06.07. Type coercion ---------------------- +## 06.07. Type coercion - Type coercion simply refer to the JavaScript ability to convert type automatically (developer does not do it but JavaScript does it for us) - Type coercion is the process of converting a value from one type to another (such as string to a number, object to boolean, and so on) - JavaScript engine converts the type as per its rules (implicit ie. automatic conversion of data type) -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -const num1 = '20'; +const num1 = "20"; const num1 = 10; -const sum = (num1) + (num2); +const sum = num1 + num2; console.log(sum); console.log(typeof sum); ``` -Section 07. Operators -===================== +# Section 07. Operators -07.01. What is the Operator? ---------------------- -- We know/use many operators since our initial school days, they are things like addition +, multiplication *, subtraction -, open-close round bracket ( ) or square bracket [ ] +## 07.01. What is the Operator? + +- We know/use many operators since our initial school days, they are things like addition +, multiplication \*, subtraction -, open-close round bracket ( ) or square bracket [ ] - Operators are symbols/keywords that tell the JavaScript engine to `perform some sort of actions` - JavaScript operators are symbols that are used to perform operations on operands - Operators used along with our variables and constants to create -expressions to implement logic and algorithms + expressions to implement logic and algorithms > **Note**: <br/> -Let us take a simple expression `var sum = 1 + 2`; -- Here 1 and 2 are called `operands` and +> Let us take a simple expression `var sum = 1 + 2`; + +- Here 1 and 2 are called `operands` and - `=` & `+` are called the `operator` - `= is the assignment` operator, `+ is the arithmetic` operator > **Syntax & Example**: `07.01.script.js` + ```javascript -// Lets take a look on simple expression +// Lets take a look on simple expression var sum = 1 + 2; -// Here 1 and 2 are called `operands` and +// Here 1 and 2 are called `operands` and // `=` & `+` are called the `operator` // `= is the assignment` operator, `+ is the arithmetic` operator ``` **JavaScript supports the following types of operators**: + 1. Arithmetic Operators 2. Assignment Operators 3. Logical Operators @@ -1416,117 +1415,119 @@ var sum = 1 + 2; 6. String Operators 7. Bitwise Operators -07.02. Arithmetic Operators ----------------------- + 07.02. Arithmetic Operators + +--- - Arithmetic operators are used to performing arithmetic operations (just like mathematics - calculations) on numbers/the operands JavaScript supports the following Arithmetic operators (List of Arithmetic operators): -| Operators | Description | Example / Result | -| ----------|---------------------------------------|-------------------------------------------------| -| + | Addition | 10 + 20 = 30 (Sum of num1 and num2) | -| - | Subtraction | 20 - 10 = 10 (Difference of num1 and num2) | -| * | Multiplication | 10 * 20 = 200 (Product of num1 and num2) | -| / | Division | 20 / 10 = 2 (Quotient of num1 and num2) | -| % | Modulus (Division Remainder) | 20 % 10 = 0 (Remainder of num1 divided by num2) | -| ++ | Increment | var num1 = 100; num1++; Now num1 = 11 | -| -- | Decrement | var num1 = 100; num1--; Now num1 = 9 | -| ** | Exponentiation (ES2016 / ES6) | 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times) | -| | | | +| Operators | Description | Example / Result | +| --------- | ----------------------------- | ------------------------------------------------------ | +| + | Addition | 10 + 20 = 30 (Sum of num1 and num2) | +| - | Subtraction | 20 - 10 = 10 (Difference of num1 and num2) | +| \* | Multiplication | 10 \* 20 = 200 (Product of num1 and num2) | +| / | Division | 20 / 10 = 2 (Quotient of num1 and num2) | +| % | Modulus (Division Remainder) | 20 % 10 = 0 (Remainder of num1 divided by num2) | +| ++ | Increment | var num1 = 100; num1++; Now num1 = 11 | +| -- | Decrement | var num1 = 100; num1--; Now num1 = 9 | +| \*\* | Exponentiation (ES2016 / ES6) | 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times) | +| | | | > **Syntax & Example**: `07.02.script.js` + ```javascript // Arithmetic operators var num1 = 10; var num2 = 4; -alert('Addition ' + (num1 + num2)); // 14 -alert('Subtraction ' + (num1 - num2)); // 6 -alert('Multiplication ' + num1 * num2); // 40 -alert('Division ' + num1 / num2); // 2.5 -alert('Modulus reminder ' + num1 % num2); // 2 -num1++ -alert('after Increment ' + num1); // 11 -num2--; -alert('after Decrement ' + num2); // 3 +alert("Addition " + (num1 + num2)); // 14 +alert("Subtraction " + (num1 - num2)); // 6 +alert("Multiplication " + num1 * num2); // 40 +alert("Division " + num1 / num2); // 2.5 +alert("Modulus reminder " + (num1 % num2)); // 2 +num1++; +alert("after Increment " + num1); // 11 +num2--; +alert("after Decrement " + num2); // 3 num1 = 10; num2 = 4; -alert('Exponentiation ' + (num1 ** num2)); // (10 ** 4) = 10* 10 * 10 * 10 = 10000 +alert("Exponentiation " + num1 ** num2); // (10 ** 4) = 10* 10 * 10 * 10 = 10000 ``` -07.03. Assignment Operators ---------------------- +## 07.03. Assignment Operators - The Assignment operators are used to assign particular values to variables JavaScript supports the following Assignment operators (List of Assignment operators): -| Operators | Description | Example / Result | -| ----------|---------------------------------------|---------------------------------------| -| = | Simple Assignment | 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable) | -| += | Add and assign | var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;) | -| -= | Subtract and assign | var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;) | -| *= | Multiply and assign | var num1 = 10; num1 *= 5; Now num1 = 50 (assigns and multiply value to variable, num1 *= 5; is equivalent to num1 = num1 * 5;) | -| /= | Divide and assign | var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;) | -| %= | Modulus and assign | var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;) | -| | | | +| Operators | Description | Example / Result | +| --------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| = | Simple Assignment | 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable) | +| += | Add and assign | var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;) | +| -= | Subtract and assign | var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;) | +| \*= | Multiply and assign | var num1 = 10; num1 _= 5; Now num1 = 50 (assigns and multiply value to variable, num1 _= 5; is equivalent to num1 = num1 \* 5;) | +| /= | Divide and assign | var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;) | +| %= | Modulus and assign | var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;) | +| | | | > **Syntax & Example**: `07.03.script.js` + ```javascript // Assignment operators var num1 = 10; -var num2 = 20 +var num2 = 20; // old methodology // num1 = num1 + num2; // console.log(num1); // 30 // new techniques -num1 += num2; +num1 += num2; console.log(num1); // 30 -// num2 -= num1; +// num2 -= num1; // console.log(num2); // 10 -// num1 *= num2; +// num1 *= num2; // console.log(num1); // 200 -// num2 /= num1; +// num2 /= num1; // console.log(num2); // 2 ``` -07.04. Logical Operators ---------------------- +## 07.04. Logical Operators - The Logical operators are used to make decisions based on multiple conditions - The logical operators are typically used to combine multiple conditional statements and evaluate JavaScript supports the following Logical operators (List of Logical operators): -| Operators | Description | Example / Result | -| ----------------|---------------------------------------|---------------------------------------| -| && | Logical AND | x && y; (True if both operands like x and y are true) | -| || | Logical OR | x || y; (True if either x or y is true)| -| ! | Logical NOT | !x; (True if x is not true) | -| | | | +| Operators | Description | Example / Result | +| ------------ | ----------- | ----------------------------------------------------- | +| && | Logical AND | x && y; (True if both operands like x and y are true) | +| || | Logical OR | x || y; (True if either x or y is true) | +| ! | Logical NOT | !x; (True if x is not true) | +| | | | > **Syntax & Example**: `07.04.01.script.js` + ```javascript // Logical operators - basic examples // && (Logical AND) - returns true if both operands are true -console.log('true && true: ', true && true); -console.log('true && false: ', true && false); -console.log('false && true: ', false && true); +console.log("true && true: ", true && true); +console.log("true && false: ", true && false); +console.log("false && true: ", false && true); // ------------------------------ // || (Logical OR) - returns true if one of the operand is true -console.log('true || true: ', true || true); -console.log('true || false: ', true || false); -console.log('false || true: ', false || true); +console.log("true || true: ", true || true); +console.log("true || false: ", true || false); +console.log("false || true: ", false || true); // ------------------------------ @@ -1534,11 +1535,13 @@ console.log('false || true: ', false || true); var isSeniorCitizen = true; var isYoungGeneration = !isSeniorCitizen; -console.log('isYoungGeneration: ', isYoungGeneration); +console.log("isYoungGeneration: ", isYoungGeneration); ``` + <hr/> > **Syntax & Example**: `07.04.02.script.js` + ```javascript // Logical operators - real world scenario/example @@ -1549,23 +1552,22 @@ var isEligibleForLoan; // check eligibility with && Logical AND operator isEligibleForLoan = isEarningHighIncome && isGoodCibilScore; -alert('isEligibleForLoan: ' + isEligibleForLoan); +alert("isEligibleForLoan: " + isEligibleForLoan); // check eligibility with || Logical OR operator isEligibleForLoan = isEarningHighIncome || isGoodCibilScore; -alert('isEligibleForLoan: ' + isEligibleForLoan); +alert("isEligibleForLoan: " + isEligibleForLoan); // ! Logical NOT var isLoanRefused = !isEligibleForLoan; -alert('isLoanRefused: ' + isLoanRefused); +alert("isLoanRefused: " + isLoanRefused); ``` -07.05. Comparison (or Relational) Operators ---------------------- -07.05. Comparison Operators ---------------------- -07.05. Relational Operators ---------------------- +## 07.05. Comparison (or Relational) Operators + +## 07.05. Comparison Operators + +## 07.05. Relational Operators - The JavaScript comparison operator compares the two operands - It compares two values in a Boolean fashion @@ -1573,54 +1575,55 @@ alert('isLoanRefused: ' + isLoanRefused); JavaScript supports the following Comparison (or Relational) operators (List of Comparison (or Relational) operators): -| Operators | Description | Example / Result | -| ----------|---------------------------------------|---------------------------------------| -| == <br/>(Loose Equality Operator) | Is equal to / identical | x == y (True if x is equal to y) | -| === <br/>(Strict Equality Operator) | Eqaul/identical value and identical type| x === y (True if x is equal to y, and they are of the same type) | -| != | Not equal to / different | x != y (True if x is not equal to y) | -| !== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) | -| < | Less than | x < y (True if x is less than y)| -| > | Greater than | x > y (True if x is greater than y)| -| <= | Less than or equal to | x <= y (True if x is less than or equal to y) | -| >= | Greater than or equal to | x >= y (True if x is greater than or equal to y)| -| | | | +| Operators | Description | Example / Result | +| ----------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------- | +| == <br/>(Loose Equality Operator) | Is equal to / identical | x == y (True if x is equal to y) | +| === <br/>(Strict Equality Operator) | Eqaul/identical value and identical type | x === y (True if x is equal to y, and they are of the same type) | +| != | Not equal to / different | x != y (True if x is not equal to y) | +| !== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) | +| < | Less than | x < y (True if x is less than y) | +| > | Greater than | x > y (True if x is greater than y) | +| <= | Less than or equal to | x <= y (True if x is less than or equal to y) | +| >= | Greater than or equal to | x >= y (True if x is greater than or equal to y) | +| | | | > **Syntax & Example**: `07.05.script.js` + ```javascript // Comparison (or Relational) operators var num1 = 25; var num2 = 35; var num3 = "25"; - -alert(num1 == num3); // true + +alert(num1 == num3); // true alert(num1 === num3); // false -alert(num1 != num2); // true +alert(num1 != num2); // true alert(num1 !== num3); // true -alert(num1 < num2); // true -alert(num1 > num2); // false -alert(num1 <= num2); // true -alert(num1 >= num2); // false +alert(num1 < num2); // true +alert(num1 > num2); // false +alert(num1 <= num2); // true +alert(num1 >= num2); // false ``` -07.06. Conditional (? or ternary) Operator ---------------------- -07.06. Conditional Operator ---------------------- -07.06. Ternary Operator ---------------------- +## 07.06. Conditional (? or ternary) Operator + +## 07.06. Conditional Operator + +## 07.06. Ternary Operator - Conditional Operator returns a value based on the condition, it is like if-else -- The conditional (ternary) operator is the only JavaScript operator that takes three operands +- The conditional (ternary) operator is the only JavaScript operator that takes three operands - The conditional operator that assigns a value to a variable based on some condition - This operator is frequently used as a shortcut/short-hand method for the if statement -- **Syntax**: variablename = (condition) ? TRUE value: FALSE value +- **Syntax**: variablename = (condition) ? TRUE value: FALSE value -| Operators | Description | Example / Result | -| ----------|---------------------------------------|---------------------------------------| -| ? | Ternary operator | var result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition) | -| | | | +| Operators | Description | Example / Result | +| --------- | ---------------- | ---------------------------------------------------------------------------------------------- | +| ? | Ternary operator | var result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition) | +| | | | > **Syntax & Example**: `07.06.script.js` + ```javascript // Conditional (? or ternary) Operator @@ -1628,44 +1631,43 @@ alert(num1 >= num2); // false var currentAge = 100; var category; -category = (currentAge < 18) ? 'Minor' : 'Major'; -alert('AGE category: ' + category); +category = currentAge < 18 ? "Minor" : "Major"; +alert("AGE category: " + category); // fees category var isAuthorisedMember = true; var fees; -fees = (isAuthorisedMember == true) ? 5 : 10; -alert('fees / charges: ' + fees); +fees = isAuthorisedMember == true ? 5 : 10; +alert("fees / charges: " + fees); ``` -07.07. String Operators ---------------------- +## 07.07. String Operators Variables can also have string values, `+ operator` can be used to concatenate strings as well as numbers. There are two operators which can also be used be for strings: -| Operators | Description | Example / Result | -| ----------|---------------------------------------|---------------------------------------| -| + | Concatenation | string1 + string2 (Concatenation of string1 and string2) | -| += | Concatenation assignment | string1 += string2 (Appends the str2 to the str1) | -| | | | +| Operators | Description | Example / Result | +| --------- | ------------------------ | -------------------------------------------------------- | +| + | Concatenation | string1 + string2 (Concatenation of string1 and string2) | +| += | Concatenation assignment | string1 += string2 (Appends the str2 to the str1) | +| | | | > **Syntax & Example**: `07.07.script.js` + ```javascript // String Operators var message1 = "Hello"; var message2 = " World!"; - + alert(message1 + message2); // Outputs: Hello World! - + message1 += message2; alert(message1); // Outputs: Hello World! ``` -07.08. Operator precedence ---------------------- +## 07.08. Operator precedence - If an expression has more than one operator, the `execution order is defined by their precedence`, or the implicit priority order of operators - Operator precedence determines/describes the way in which operators are parsed with respect to each other / `order in which operations are performed` @@ -1673,28 +1675,27 @@ alert(message1); // Outputs: Hello World! - If many operations have the same precedence (like addition and subtraction), they are `computed from left to right` > **Syntax & Example**: `07.08.script.js` + ```javascript // Operator precedence -var result1 = 10 + 2 * 5 -alert('10 + 2 * 5 = ' + result1); // answer is 20 NOT 60 (12 * 5 ), actually * or multiplication have higher precedence so the actual calculation is like 10 + ( 2*5 ) = 10 + 10 = 20 +var result1 = 10 + 2 * 5; +alert("10 + 2 * 5 = " + result1); // answer is 20 NOT 60 (12 * 5 ), actually * or multiplication have higher precedence so the actual calculation is like 10 + ( 2*5 ) = 10 + 10 = 20 -// change precedence with `parentheses ()` +// change precedence with `parentheses ()` var result2 = (10 + 2) * 5; -alert('(10 + 2) * 5 = ' + result2); // (12) * 5 = 60 +alert("(10 + 2) * 5 = " + result2); // (12) * 5 = 60 // same precedence operators -var result3 = 10 + 5 - 2 -alert('10 + 5 - 2 = ' + result3); // 13 first addition than subtraction +var result3 = 10 + 5 - 2; +alert("10 + 5 - 2 = " + result3); // 13 first addition than subtraction var result4 = 10 + (5 - 2); -alert('10 + (5 - 2) = ' + result4); // 13 first subtraction ie. ( ) than addition +alert("10 + (5 - 2) = " + result4); // 13 first subtraction ie. ( ) than addition ``` -Section 08. Functions -===================== +# Section 08. Functions -08.01. What is a Function? ---------------------- +## 08.01. What is a Function? - A function is basically a `group of statements that perform specific tasks/operations` - Functions provide a way to `create reusable code packages` which are more portable and easier to debug @@ -1704,12 +1705,12 @@ Section 08. Functions - Wrapping up / making smaller chunks of statements / reusable codes together for readability or separation of concern/proper organization is functions – (Grouping of a repetitive task) - Functions (logical block of code) are one of the most important control structure in any programming language - In other languages, it might be called `MODULES, SUBROUTINES(SUB-ROUTINES)` -- There are two steps to utilize function: - 1. create/define a function with `function` keyword +- There are two steps to utilize function: + 1. create/define a function with `function` keyword 2. call/invoke a function > **Note**: <br/> -Best Practice - First Define function than call/envoke it! +> Best Practice - First Define function than call/envoke it! #### 08.01.01. Here are some advantages of using functions: @@ -1720,20 +1721,21 @@ Best Practice - First Define function than call/envoke it! #### 08.01.02. Function Definition / Function Declaration / Creating Function -- The function declaration starts by using the `function keyword`, -- followed by a `unique function name`, -- a list of `parameters in parentheses` i.e. () (that might be empty), +- The function declaration starts by using the `function keyword`, +- followed by a `unique function name`, +- a list of `parameters in parentheses` i.e. () (that might be empty), - and a statement block surrounded by `curly braces { }` > **Syntax & Example**: `08.01.script.js` + ```javascript //1. define / declare / create function -function showMessage () { - //Body of function +function showMessage() { + //Body of function //code to be executed - console.log('welcome to JavaScript function'); - alert('welcome to JavaScript function'); + console.log("welcome to JavaScript function"); + alert("welcome to JavaScript function"); } ``` @@ -1742,6 +1744,7 @@ function showMessage () { - Defined function can be invoked/called/run from anywhere in the document, by typing `function name followed by a set of parentheses, like functionName()` > **Syntax & Example**: `08.01.script.js` + ```javascript //2. invoke / call the function @@ -1760,13 +1763,15 @@ Usually, Function name starts with: - "checkSomething" – check something and return a boolean, etc. Examples of function names: + - getSum(); - createFields(); - calcAge(); - checkUserType(); -08.02. Types of Function ---------------------- + 08.02. Types of Function + +--- - Regular Function - Parameterized Function @@ -1777,15 +1782,16 @@ Examples of function names: - Simple/Normal function which we use daily to perform some action/task > **Syntax & Example**: `08.02.01.script.js` + ```javascript -var name = 'Dinanath'; +var name = "Dinanath"; //1. define / declare / create function -function sayHello () { - //Body of function +function sayHello() { + //Body of function //code to be executed - console.log('Hello ' + name); - alert('Hello ' + name); + console.log("Hello " + name); + alert("Hello " + name); } //2. invoke / call the function @@ -1798,26 +1804,27 @@ sayHello(); - You can specify parameters when you define your function to accept input values at run time > **Syntax & Example**: `08.02.02.01.script.js` + ```javascript // Parameterized function //1. define / declare / create function -function sayHello (name) { - //Body of function +function sayHello(name) { + //Body of function //code to be executed - console.log('Hello ' + name); - alert('Hello ' + name); + console.log("Hello " + name); + alert("Hello " + name); } //2. invoke / call the function -sayHello('Dinanath'); +sayHello("Dinanath"); -sayHello('Dino'); +sayHello("Dino"); // ------------------------------ var total; -function calculateSum (num1, num2) { +function calculateSum(num1, num2) { total = num1 + num2; console.log(total); } @@ -1831,27 +1838,28 @@ calculateSum(100, 200); With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to the function when it is called these default parameters values will be used. > **Syntax & Example**: `08.02.02.02.script.js` + ```javascript // Parameterized function with default parameters //1. define / declare / create function -function sayHello (name = 'User') { - //Body of function +function sayHello(name = "User") { + //Body of function //code to be executed - console.log('Hello ' + name); - alert('Hello ' + name); + console.log("Hello " + name); + alert("Hello " + name); } //2. invoke / call the function sayHello(); -sayHello('Amber'); +sayHello("Amber"); // ------------------------------ var total; -function calculateSum (num1=1, num2=2) { +function calculateSum(num1 = 1, num2 = 2) { total = num1 + num2; console.log(total); } @@ -1867,26 +1875,26 @@ calculateSum(100, 200); - The return statement usually placed as the last line of the function > **Syntax & Example**: `08.02.03.script.js` + ```javascript // Return type function //1. define / declare / create function -function getSum (num1, num2) { - //Body of function +function getSum(num1, num2) { + //Body of function //code to be executed var sum = num1 + num2; - return(sum); + return sum; } //2. invoke / call the function -console.log(getSum(10,20)); -console.log(getSum(100,200)); +console.log(getSum(10, 20)); +console.log(getSum(100, 200)); -var total = getSum(50,50); +var total = getSum(50, 50); alert(total); ``` -08.03. Different ways to define Function ---------------------- +## 08.03. Different ways to define Function The syntax that we've used before to create functions is called `function declaration`. There is another syntax for creating a function that is called a `function expression` and `Immediately invoked function expression (IIFE)` @@ -1899,6 +1907,7 @@ The syntax that we've used before to create functions is called `function declar - Named function expression > **Syntax & Example**: `08.03.02.01.script.js` + ```javascript // function declaration (Regular / normal function) function getSum1(num1, num2) { @@ -1909,21 +1918,22 @@ function getSum1(num1, num2) { // ------------------------------ // function expression - Anonymus -var getSum2 = function(num1, num2) { - var total = num1 + num2; - return total; +var getSum2 = function (num1, num2) { + var total = num1 + num2; + return total; }; -alert(getSum2(10,20)); +alert(getSum2(10, 20)); // ------------------------------ // assign function to another variable var sum1 = getSum2; -alert(sum1(100,200)); +alert(sum1(100, 200)); ``` -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // function expression - named var getSum2 = function getTotal(num1, num2) { @@ -1931,13 +1941,13 @@ var getSum2 = function getTotal(num1, num2) { return total; }; -alert(getSum2(10,20)); +alert(getSum2(10, 20)); // ------------------------------ // assign function to another variable var sum1 = getSum2; -alert(sum1(5,10)); +alert(sum1(5, 10)); ``` #### 08.03.03. Immediately invoked function expression (IIFE) @@ -1946,22 +1956,22 @@ alert(sum1(5,10)); - Declare and run the function at the same time > **Syntax & Example**: `08.03.03.script.js` + ```javascript // Immediately invoked function expression (IIFE) (function () { - console.log('Welcome to Immediately invoked function expression (IIFE)'); -}()); + console.log("Welcome to Immediately invoked function expression (IIFE)"); +})(); - -(function(userName) { - console.log('Welcome', userName); -})('Dinanath'); +(function (userName) { + console.log("Welcome", userName); +})("Dinanath"); ``` -08.04. String Methods and Concatenation ---------------------- +## 08.04. String Methods and Concatenation + +> **Syntax & Example**: -> **Syntax & Example**: ```javascript const firstName = 'Dinanath'; @@ -2011,7 +2021,7 @@ console.log(firstName.charAt(firstName.length - 1)); // replace(); let replaceString = ('Dinanath', 'DJ'); -console.log('My name is:', replaceString); +console.log('My name is:', replaceString); // substring(); console.log(firstName.substring(0,4)); @@ -2037,10 +2047,9 @@ console.log(courses.split(',')); ``` -08.05. Template String ---------------------- -08.05. Template Literals ---------------------- +## 08.05. Template String + +## 08.05. Template Literals - ES6 new feature `Strings Template` offers a convenient way to work with string concatenation/interpolation - Template literals provide an easy and clean way to create multi-line strings and perform string interpolation @@ -2050,7 +2059,8 @@ console.log(courses.split(',')); - It is part of ES6 but compatible with all the modern browsers and its latest versions -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript //old plain javascript approach @@ -2058,7 +2068,7 @@ let user = 'Dinanath'; let greetMessage1 = 'Welcome' + ' ' + user + ' ' + 'to JavaScript.'; console.log(greetMessage1); - + console.log('// ------------------------------'); const firstName = 'Dinanath'; @@ -2114,8 +2124,9 @@ Section 09. Loops and Iterations 5. for...of loop (ES6) 6. for...each -09.01. The for loop ---------------------- + 09.01. The for loop + +--- - The `For` loop is used to run a piece of code a `set amount of times` - Loops through a block of code until the `counter reach a specified number` @@ -2124,6 +2135,7 @@ Section 09. Loops and Iterations - For loop consists of 3 statements (), mostly `i = index` is used for loop initialization > **Syntax & Example**: `09.01.01.script.js` + ```javascript // for loop @@ -2131,53 +2143,54 @@ Section 09. Loops and Iterations // Code to be executed } */ - /* for(variable definition/index/initialization; condition checking; increment/decrement expression) { // Code to be executed } */ -for (let i=1; i<=5; i++) { - alert('Hello, The current index/num is: ' + i); - document.write('<li>Hello, The current index/num is: ' + i + '</li>'); - console.log('Hello, The current index/num is: ' + i); +for (let i = 1; i <= 5; i++) { + alert("Hello, The current index/num is: " + i); + document.write("<li>Hello, The current index/num is: " + i + "</li>"); + console.log("Hello, The current index/num is: " + i); } ``` ### 09.01.01. The for loop - Reverse order > **Syntax & Example**: `09.01.02.script.js` + ```javascript // for loop - reverse order for (let i = 5; i >= 1; i--) { - alert('Hello, The current index/num is: ' + i); - document.write('<li>Hello, The current index/num is: ' + i + '</li>'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("<li>Hello, The current index/num is: " + i + "</li>"); + console.log("Hello, The current index/num is: " + i); } ``` ### 09.01.02. The for loop - Find Even or Odd number > **Syntax & Example**: `09.01.03.script.js` + ```javascript // for loop - to find out odd even number for (let i = 1; i <= 10; i++) { if (i % 2 == 0) { - console.log('The current index/num is EVEN : ' + i); + console.log("The current index/num is EVEN : " + i); } /* else { console.log('The current index/num is ODD : ' + i); } */ } ``` -09.02. The while loop ---------------------- +## 09.02. The while loop - Loops through a block of code until the specified condition evaluates to true - In For loop, a variable is part of a loop, but in While loop, we need to declare variable externally > **Syntax & Example**: `09.02.01.script.js` + ```javascript // while loop @@ -2188,22 +2201,22 @@ for (let i = 1; i <= 10; i++) { let i = 1; while (i <= 5) { - alert('Hello, The current index/num is: ' + i); - document.write('<li>Hello, The current index/num is: ' + i + '</li>'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("<li>Hello, The current index/num is: " + i + "</li>"); + console.log("Hello, The current index/num is: " + i); i++; } ``` -09.03. The do while loop ---------------------- -09.03. The do...while loop ---------------------- +## 09.03. The do while loop + +## 09.03. The do...while loop - The do...while loop is similar to the while loop except that the `condition check happens at the end of the loop` - The do...while loop will always be `executed at least once (before checking if the condition is true)`, even if the condition is false > **Syntax & Example**: `09.03.01.script.js` + ```javascript // do...while loop @@ -2215,24 +2228,23 @@ while(condition);*/ let i = 1; do { - alert('Hello, The current index/num is: ' + i); - document.write('<li>Hello, The current index/num is: ' + i + '</li>'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("<li>Hello, The current index/num is: " + i + "</li>"); + console.log("Hello, The current index/num is: " + i); i++; -} -while (i <= 5); +} while (i <= 5); ``` -09.04. The for in loop ---------------------- -09.04. The for...in loop ---------------------- +## 09.04. The for in loop + +## 09.04. The for...in loop - The for-in loop is a special type of a loop that `iterates over the properties of an object or the elements of an array` #### 09.04.01. The for...in Loop - array > **Syntax & Example**: `09.04.01.script.js` + ```javascript // for...in loop @@ -2243,17 +2255,18 @@ while (i <= 5); // An array with some elements let arrColors = ["Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Black"]; -// Loop through all the elements in the array +// Loop through all the elements in the array for (let color in arrColors) { - alert('Color is: ' + arrColors[color]); - document.write('<li>Color is: ' + arrColors[color] + '</li>'); - console.log('Color is: ' + arrColors[color]); + alert("Color is: " + arrColors[color]); + document.write("<li>Color is: " + arrColors[color] + "</li>"); + console.log("Color is: " + arrColors[color]); } ``` #### 09.04.02. The for...in Loop - object > **Syntax & Example**: `09.04.02.script.js` + ```javascript // for...in loop @@ -2261,20 +2274,26 @@ for (let color in arrColors) { // Code to be executed }*/ -// An object with some properties -let objEmployee = {'emp_name': 'Dinanath', 'emp_addres': 'Mumbai', 'emp_id': '029', 'emp_age':35}; +// An object with some properties +let objEmployee = { + emp_name: "Dinanath", + emp_addres: "Mumbai", + emp_id: "029", + emp_age: 35, +}; -// Loop through all the properties in the object +// Loop through all the properties in the object for (emp in objEmployee) { - alert('Employee '+ emp + ' is: ' + objEmployee[emp]); - document.write('<li>Employee '+ emp + ' is: ' + objEmployee[emp] + '</li>'); - console.log('Employee '+ emp + ' is: ' + objEmployee[emp]); + alert("Employee " + emp + " is: " + objEmployee[emp]); + document.write("<li>Employee " + emp + " is: " + objEmployee[emp] + "</li>"); + console.log("Employee " + emp + " is: " + objEmployee[emp]); } ``` #### 09.04.03. The for...in Loop - Inbuilt JavaScript objects > **Syntax & Example**: `09.04.03.script.js` + ```javascript // for...in loop @@ -2285,21 +2304,21 @@ for (emp in objEmployee) { // Loop through all the properties in the inbuilt object - window, document, navigator for (props in window) { // alert('document object properties ' + props); - document.write('<li>document object properties ' + props + '</li>'); - console.log('document object properties ' + props); + document.write("<li>document object properties " + props + "</li>"); + console.log("document object properties " + props); } ``` -09.05. The for of loop ---------------------- -09.05. The for...of loop (ES6) ---------------------- +## 09.05. The for of loop + +## 09.05. The for...of loop (ES6) - Loops over `iterable objects such as arrays, strings`, etc. - ES6 introduces a new for-of loop which allows us to iterate over arrays or strings very easily - The code inside the loop is executed for each element of the iterable object > **Syntax & Example**: `09.05.01.script.js` + ```javascript // for...of loop @@ -2308,23 +2327,30 @@ for (props in window) { } */ // Iterating over an array -let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; +let arrDays = [ + "Monday", + "TuesDay", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", +]; for (let day of arrDays) { console.log(day); - document.write('<li>' + day + '</li>'); + document.write("<li>" + day + "</li>"); } // Iterating over string -let name = 'JavaScript'; +let name = "JavaScript"; for (let letter of name) { - document.write(letter + ','); - console.log(letter + ','); + document.write(letter + ","); + console.log(letter + ","); } ``` -09.06. Break and Continue statement ---------------------- +## 09.06. Break and Continue statement - `break` and `continue` keywords/statement can change `how the loop behaves` - `break` and `continue` keywords can be used in all loops to stop or continue the loop @@ -2332,11 +2358,20 @@ for (let letter of name) { - The `continue` statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block > **Syntax & Example**: `09.06.01.script.js` + ```javascript // break continue statement /* break */ -let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; +let arrDays = [ + "Monday", + "TuesDay", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", +]; let i = 1; while (i <= 10) { @@ -2344,10 +2379,10 @@ while (i <= 10) { break; } console.log(i); - i++ + i++; } -console.log('// ------------------------------'); +console.log("// ------------------------------"); for (let i = 0; i <= arrDays.length; i++) { if (i == 3) { @@ -2356,7 +2391,7 @@ for (let i = 0; i <= arrDays.length; i++) { console.log(arrDays[i]); } -console.log('// ------------------------------'); +console.log("// ------------------------------"); /* continue */ i = 1; @@ -2366,48 +2401,46 @@ while (i <= 20) { i++; continue; // skip rest of the loop body - i + 100; // non of use - console.log('just in even num continue'); // non of use + i + 100; // non of use + console.log("just in even num continue"); // non of use } - console.log('Odd Number ', i); + console.log("Odd Number ", i); i++; } -console.log('// ------------------------------'); +console.log("// ------------------------------"); for (i = 1; i <= 10; i++) { if (i === 5) { continue; // skip rest of the loop body - console.log('just after 5 continue...'); // non of use + console.log("just after 5 continue..."); // non of use } console.log(i); } -console.log('// ------------------------------'); - -for(let int = 0; int < 10; int++) { +console.log("// ------------------------------"); - if(int === 2) { - console.log('2 is favorite EVEN number'); +for (let int = 0; int < 10; int++) { + if (int === 2) { + console.log("2 is favorite EVEN number"); continue; } - if(int === 5) { - console.log('at 5 stop the loop'); + if (int === 5) { + console.log("at 5 stop the loop"); break; } - console.log('current Number is:', int); + console.log("current Number is:", int); } - ``` -09.07. for each loop ---------------------- -09.07. for...each loop ---------------------- +## 09.07. for each loop + +## 09.07. for...each loop > **Syntax & Example**: `` + ```javascript let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; @@ -2418,10 +2451,9 @@ arrDays.forEach(function(day)){ ``` -Section 10. Conditions -===================== -Section 10. Conditions - Control Flow -===================== +# Section 10. Conditions + +# Section 10. Conditions - Control Flow - Conditional statements are used to perform different action based on different condition - Conditional statements allow the developer to make correct decisions and perform right actions as per condition @@ -2435,10 +2467,11 @@ Section 10. Conditions - Control Flow 3. If...else if...else Statement 4. Switch...Case Statement -10.01. The if statement ---------------------- -10.01. The if statement and comparison operators ---------------------- + 10.01. The if statement + +--- + +## 10.01. The if statement and comparison operators - If the conditional statement is the simplest and basic control statement make decisions and execute statements conditionally - The if statement is used to execute a block of code `only if the specified condition evaluates to true` @@ -2447,9 +2480,10 @@ Section 10. Conditions - Control Flow If conditional statements are used to evaluate some kind of condition and do something/perform some actions based on the result > **Note**: <br/> -Use `if` to specify a block of code to be executed, `if a specified condition is true` +> Use `if` to specify a block of code to be executed, `if a specified condition is true` > **Syntax & Example**: `10.01.01.script.js` + ```javascript // if conditional statement @@ -2458,16 +2492,16 @@ Use `if` to specify a block of code to be executed, `if a specified condition is } */ -let user = 'Dinanath'; +let user = "Dinanath"; -if (user == 'Dinanath') { - console.log('Welcome Dinanath!'); - window.alert('Welcome Dinanath!'); +if (user == "Dinanath") { + console.log("Welcome Dinanath!"); + window.alert("Welcome Dinanath!"); } -if (user == 'Dinanath') { - console.log('Welcome Authorised User: ' + user + '!'); - window.alert('Welcome Authorised User: ' + user + '!'); +if (user == "Dinanath") { + console.log("Welcome Authorised User: " + user + "!"); + window.alert("Welcome Authorised User: " + user + "!"); } // ------------------------------ @@ -2475,29 +2509,28 @@ if (user == 'Dinanath') { let age = 20; if (age >= 18) { - console.log('MAJOR! Eligible for Voting'); - window.alert('MAJOR! Eligible for Voting'); + console.log("MAJOR! Eligible for Voting"); + window.alert("MAJOR! Eligible for Voting"); } // ------------------------------ let currentHours = 10; -if(currentHours < 12) { - console.log('Good Morning!'); - window.alert('Good Morning!'); +if (currentHours < 12) { + console.log("Good Morning!"); + window.alert("Good Morning!"); } -if(currentHours >=6 && currentHours < 12) { - console.log('Good Morning!'); - window.alert('Good Morning!'); +if (currentHours >= 6 && currentHours < 12) { + console.log("Good Morning!"); + window.alert("Good Morning!"); } ``` -10.02. The if else statement ---------------------- -10.02. The if...else statement ---------------------- +## 10.02. The if else statement + +## 10.02. The if...else statement - The JavaScript `if...else statement` is used to execute the code `weather condition is true or false` - The developer can enhance the decision-making capabilities by providing an alternative choice through adding an `else` statement to the `if` statement @@ -2505,9 +2538,10 @@ if(currentHours >=6 && currentHours < 12) { - If the condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed > **Note**: <br/> -Use `else` to specify a block of code to be executed, `if the same condition is false` +> Use `else` to specify a block of code to be executed, `if the same condition is false` > **Syntax & Example**: `10.02.01.script.js` + ```javascript // if...else conditional statement @@ -2518,14 +2552,14 @@ else{ // content to be executed if condition is false - statements_2 }*/ -let user = 'Ambar'; +let user = "Ambar"; -if (user == 'Dinanath') { - console.log('Welcome Dinanath!'); - window.alert('Welcome Dinanath!'); +if (user == "Dinanath") { + console.log("Welcome Dinanath!"); + window.alert("Welcome Dinanath!"); } else { - console.log('Welcome Guest!'); - window.alert('Welcome Guest!'); + console.log("Welcome Guest!"); + window.alert("Welcome Guest!"); } // ------------------------------ @@ -2533,38 +2567,38 @@ if (user == 'Dinanath') { let age = 15; if (age >= 18) { - console.log('MAJOR! Eligible for Voting'); - window.alert('MAJOR! Eligible for Voting'); + console.log("MAJOR! Eligible for Voting"); + window.alert("MAJOR! Eligible for Voting"); } else { - console.log('MINOR! NOT Eligible for Voting'); - window.alert('MINOR! NOT Eligible for Voting'); + console.log("MINOR! NOT Eligible for Voting"); + window.alert("MINOR! NOT Eligible for Voting"); } // ------------------------------ let currentHours = 10; -if(currentHours < 12) { - console.log('Good Morning!'); - window.alert('Good Morning!'); +if (currentHours < 12) { + console.log("Good Morning!"); + window.alert("Good Morning!"); } else { - console.log('Good Evening!'); - window.alert('Good Evening!'); + console.log("Good Evening!"); + window.alert("Good Evening!"); } ``` -10.03. The if else if else statement ---------------------- -10.03. The if...else, if...else statement ---------------------- +## 10.03. The if else if else statement + +## 10.03. The if...else, if...else statement - The `if...else if...else` a special statement that is used to `combine multiple if...else statements` - It is an advanced form of if...else that allows us to `make a correct decision out of several conditions` > **Note**: <br/> -Use `else if` to specify a new condition to test, `if the first condition is false` +> Use `else if` to specify a new condition to test, `if the first condition is false` > **Syntax & Example**: `10.03.01.script.js` + ```javascript // If...else if...else conditional statement @@ -2580,54 +2614,54 @@ let num1 = 200; let num2 = 100; if (num1 == num2) { - console.log('Both numbers are equal'); -} else if (num1 < num2 ) { - console.log('Number2 is greater!'); + console.log("Both numbers are equal"); +} else if (num1 < num2) { + console.log("Number2 is greater!"); } else { - console.log('Number1 is greater!'); + console.log("Number1 is greater!"); } // ------------------------------ -let age = 15; +let age = 15; if (age >= 60) { - console.log('SINIOR CIRIZEN!'); + console.log("SINIOR CIRIZEN!"); } else if (age < 18) { - console.log('MINOR!'); + console.log("MINOR!"); } else { - console.log('MAJOR - Middle Age!'); + console.log("MAJOR - Middle Age!"); } // ------------------------------ let currentHours = 15; -if(currentHours >=6 && currentHours< 12) { - console.log('Good Morning!'); - window.alert('Good Morning!'); -} else if (currentHours >12 && currentHours <=18) { - console.log('Good AfterNoon!'); - window.alert('Good AfterNoon!'); +if (currentHours >= 6 && currentHours < 12) { + console.log("Good Morning!"); + window.alert("Good Morning!"); +} else if (currentHours > 12 && currentHours <= 18) { + console.log("Good AfterNoon!"); + window.alert("Good AfterNoon!"); } else { - console.log('Good Evening!'); - window.alert('Good Evening!'); + console.log("Good Evening!"); + window.alert("Good Evening!"); } ``` -10.04. The switch case statement ---------------------- -10.04. The switch...case statement ---------------------- +## 10.04. The switch case statement + +## 10.04. The switch...case statement - The switch...case statement is alternative to an if...else if...else statement, both do almost the same thing - This matches the `case` and the `value of condition` and if the case matches, the subsequent block is executed and if none of the case matches `default block` is executed - The JavaScript switch statement is used to execute one code from multiple blocks of expressions > **Note**: <br/> -Use `switch` to specify many `alternative blocks of code to be executed` +> Use `switch` to specify many `alternative blocks of code to be executed` > **Syntax & Example**: `10.04.01.script.js` + ```javascript // switch...case conditional statement @@ -2642,61 +2676,61 @@ Use `switch` to specify many `alternative blocks of code to be executed` // Code to be executed if variable/expression is different from all values } */ -let grade = 'B'; // A.B,C, or something +let grade = "B"; // A.B,C, or something switch (grade) { - case 'A': - console.log('Great Job! - A Grade'); + case "A": + console.log("Great Job! - A Grade"); break; - case 'B': - console.log('Good! - B Grade'); + case "B": + console.log("Good! - B Grade"); break; - case 'C': - console.log('Congratulations! - Passed'); + case "C": + console.log("Congratulations! - Passed"); break; default: - console.log('Sorry! - Failed...Keep trying!'); + console.log("Sorry! - Failed...Keep trying!"); break; } // ------------------------------ -let sweets = ''; //cake, chocolates, biscuits +let sweets = ""; //cake, chocolates, biscuits switch (sweets) { - case 'chocolates': - console.log('Chubby Chocolates!'); + case "chocolates": + console.log("Chubby Chocolates!"); break; - case 'cake': - console.log('Happy BirthDay Cake!'); + case "cake": + console.log("Happy BirthDay Cake!"); break; - case 'biscuits': - console.log('Enjoy Biscuits!'); + case "biscuits": + console.log("Enjoy Biscuits!"); break; default: - console.log('No Sweets! Try some other sweets!'); + console.log("No Sweets! Try some other sweets!"); break; } // ------------------------------ -const color = 'red'; +const color = "red"; -switch(color) { - case 'red': - console.log('The Dark RED'); +switch (color) { + case "red": + console.log("The Dark RED"); break; - case 'green': - console.log('Go Green'); + case "green": + console.log("Go Green"); break; - case 'blue': - console.log('Boys are Blue'); + case "blue": + console.log("Boys are Blue"); break; - case 'yellow': - console.log('Golden Yellow'); + case "yellow": + console.log("Golden Yellow"); break; default: - console.log('Its some other Color, Enter correct color'); + console.log("Its some other Color, Enter correct color"); break; } @@ -2705,39 +2739,36 @@ switch(color) { let currentDate = new Date(); let currentDay; -switch(currentDate.getDay()) { +switch (currentDate.getDay()) { case 0: - currentDay = 'Sunday'; + currentDay = "Sunday"; break; case 1: - currentDay = 'Monday'; + currentDay = "Monday"; break; case 2: - currentDay = 'Tuesday'; + currentDay = "Tuesday"; break; case 3: - currentDay = 'Wednesday'; + currentDay = "Wednesday"; break; case 4: - currentDay = 'Thursday'; + currentDay = "Thursday"; break; case 5: - currentDay = 'Friday'; + currentDay = "Friday"; break; case 6: - currentDay = 'Saturday'; + currentDay = "Saturday"; break; } console.log(`Today is ${currentDay}!`); - ``` -Section 11. Array -===================== +# Section 11. Array -11.01. What is an Array? ---------------------- +## 11.01. What is an Array? - An Array is a special type of variable/object which `consists of / stores multiple values` - Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name @@ -2750,49 +2781,52 @@ Section 11. Array #### Different ways to create/define an Array There are 3 main ways to construct an array: -1. By array literal + +1. By array literal 2. By creating an instance of Array directly (using the new keyword) 3. By using an Array constructor (using the new keyword) -11.02. Create Array by array literal ---------------------- + 11.02. Create Array by array literal + +--- - The simplest way to create an array in JavaScript is enclosing a `comma-separated list of values in square brackets [ ]` - var myArray = [element0, element1, ..., elementN]; > **Syntax & Example**: `11.02.01.script.js` + ```javascript // create array with array literal ie. [] square bracket // var myArray = [element0, element1, ..., elementN]; -var arrColors = ['Red', 'Green', 'Blue', 'Orange']; +var arrColors = ["Red", "Green", "Blue", "Orange"]; console.log(arrColors); // show all elements // ------------------------------ -var arrCities = ['Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai']; +var arrCities = ["Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai"]; console.log(arrCities[1]); // show 1st index ie. 2nd positioned element // ------------------------------ var arrTechnologies = []; -arrTechnologies[0] = 'Java'; -arrTechnologies[1] = 'Python'; -arrTechnologies[2] = 'C'; +arrTechnologies[0] = "Java"; +arrTechnologies[1] = "Python"; +arrTechnologies[2] = "C"; console.log(arrTechnologies); -console.log('Total Elements: ' + arrTechnologies.length); +console.log("Total Elements: " + arrTechnologies.length); ``` -11.03. Create Array by creating an instance of array directly ---------------------- -11.03. Create Array by creating an instance of array directly (using `new` keyword) ---------------------- +## 11.03. Create Array by creating an instance of array directly + +## 11.03. Create Array by creating an instance of array directly (using `new` keyword) - Array instance can be created using the `new` keyword `new Array()` - var myArray = new Array(); OR var myArray = Array(); > **Syntax & Example**: `11.03.01.script.js` + ```javascript // create array with new keyword @@ -2800,10 +2834,10 @@ console.log('Total Elements: ' + arrTechnologies.length); var arrColors = new Array(); -arrColors[0] = 'Red' -arrColors[1] = 'Green' -arrColors[2] = 'Blue' -arrColors[3] = 'Orange' +arrColors[0] = "Red"; +arrColors[1] = "Green"; +arrColors[2] = "Blue"; +arrColors[3] = "Orange"; console.log(arrColors); // show all elements // read/get array items/elements @@ -2814,11 +2848,11 @@ for (let i = 0; i < arrColors.length; i++) { // ------------------------------ var arrCities = Array(); -arrCities[0] = 'Delhi'; -arrCities[1] = 'Mumbai'; -arrCities[2] = 'DeKolkotalhi'; -arrCities[3] = 'Bengaluru'; -arrCities[4] = 'Chennai'; +arrCities[0] = "Delhi"; +arrCities[1] = "Mumbai"; +arrCities[2] = "DeKolkotalhi"; +arrCities[3] = "Bengaluru"; +arrCities[4] = "Chennai"; console.log(arrCities); // show all elements // ------------------------------ @@ -2827,42 +2861,49 @@ var arrTechnologies = new Array(); // add new array items/elements for (let i = 0; i <= 5; i++) { - arrTechnologies[i] = 'JavaScript'; + arrTechnologies[i] = "JavaScript"; } console.log(arrTechnologies); // show all elements ``` -11.04. Create Array by using an array constructor ---------------------- -11.04. Create Array by using an array constructor (using `new` keyword) ---------------------- +## 11.04. Create Array by using an array constructor + +## 11.04. Create Array by using an array constructor (using `new` keyword) - Array instance can be created using the `new` keyword `new Array() passing arguments` in constructor so that we don't have to provide value explicitly - var myArray = new Array(element0, element1, ..., elementN); > **Syntax & Example**: `11.04.01.script.js` + ```javascript // create array with new keyword Array constructor passing parameter // var myArray = new Array(element0, element1, ..., elementN); -var arrColors = new Array('Red', 'Green', 'Blue', 'Orange'); +var arrColors = new Array("Red", "Green", "Blue", "Orange"); console.log(arrColors); // show all elements // ------------------------------ -var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai'); +var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai"); console.log(arrCities); // show all elements // ------------------------------ -var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3'); +var arrJsFrameworks = new Array( + "jQuery", + "Angular", + "React", + "Node", + "Vue", + "Express", + "D3" +); console.log(arrJsFrameworks); // show all elements ``` -11.05. Getting the Length of an Array ---------------------- +## 11.05. Getting the Length of an Array - The `length` property returns the `length of an array`, `total number of elements` in an array - `length` property brings back an `array length - the fixed amount of items` stored in the array @@ -2871,29 +2912,37 @@ console.log(arrJsFrameworks); // show all elements - myarray.length > **Syntax & Example**: `11.05.01.script.js` + ```javascript // get/retrieve/find array length // myarray.length -var arrColors = new Array('Red', 'Green', 'Blue', 'Orange'); +var arrColors = new Array("Red", "Green", "Blue", "Orange"); console.log(arrColors.length); // ------------------------------ -var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai'); +var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai"); console.log(arrCities.length); // ------------------------------ -var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3'); +var arrJsFrameworks = new Array( + "jQuery", + "Angular", + "React", + "Node", + "Vue", + "Express", + "D3" +); console.log(arrJsFrameworks.length); ``` -11.06. Accessing Looping through an Array Elements ---------------------- -11.06. Loop through an Array Elements ---------------------- +## 11.06. Accessing Looping through an Array Elements + +## 11.06. Loop through an Array Elements - Array elements can be accessed by their `index using the square bracket notation ie. [index]` - Arrays are `zero-indexed` i.e. the first element of an array is at index/position 0 @@ -2903,36 +2952,44 @@ console.log(arrJsFrameworks.length); - myarray[indexNumber], myarray[0] // get first array element > **Syntax & Example**: `11.06.01.script.js` + ```javascript // access/loop through array element // myarray[indexNumber], myarray[0] -var arrColors = new Array('Red', 'Green', 'Blue', 'Orange'); +var arrColors = new Array("Red", "Green", "Blue", "Orange"); console.log(arrColors[0]); // Red console.log(arrColors[2]); // Blue // ------------------------------ -var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota', 'Bengaluru', 'Chennai'); +var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai"); console.log(arrCities[1]); // Mumbai console.log(arrCities[4]); // Chennai // ------------------------------ -var arrJsFrameworks = new Array('jQuery', 'Angular', 'React', 'Node', 'Vue', 'Express', 'D3'); +var arrJsFrameworks = new Array( + "jQuery", + "Angular", + "React", + "Node", + "Vue", + "Express", + "D3" +); console.log(arrJsFrameworks[3]); // Node console.log(arrJsFrameworks[5]); // Express // Loop through an Array Elements for (let i = 0; i < arrJsFrameworks.length; i++) { - document.write('<li>'+arrJsFrameworks[i] + '</li>'); + document.write("<li>" + arrJsFrameworks[i] + "</li>"); } ``` -11.07. Adding Editing an Array Elements ---------------------- +## 11.07. Adding Editing an Array Elements - One can add/edit an array element by simply specifying `array[index] and value` ie. `myarray[5]='value'` - If array `index exists it will simply edit` the old value and update the array else it will add an element to the array @@ -2941,64 +2998,65 @@ for (let i = 0; i < arrJsFrameworks.length; i++) { - myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value') > **Syntax & Example**: `11.07.01.script.js` + ```javascript // add/edit array element // myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value') -var arrColors = new Array('Red', 'Green', 'Blue', 'Orange'); +var arrColors = new Array("Red", "Green", "Blue", "Orange"); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // add an element at the end of the array -arrColors.push('Cyan'); +arrColors.push("Cyan"); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // add multiple elements at the end of the array -arrColors.push('Magenta','Yellow'); +arrColors.push("Magenta", "Yellow"); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // ------------------------------ // add multiple elements at the start of the array -arrColors.unshift('Black','White'); +arrColors.unshift("Black", "White"); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // ------------------------------ // edit 1st index ie. 'white' to 'pink' -arrColors[1] = 'pink'; +arrColors[1] = "pink"; console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); ``` -11.08. Removing Deleting an Array Elements ---------------------- +## 11.08. Removing Deleting an Array Elements - `pop()` method `remove the last element` from an array - `shift()` method remove the `first element` from an array - myarray.pop(), myarray.shift() > **Note**: <br/> -The `push() and pop() methods runs faster` than unshift() and shift(). Because push() and pop() methods add and remove elements at the end of an array, therefore, the elements do not move. unshift() and shift() add and remove elements at the beginning of the array that requires re-indexing/re-structuring of the whole array. +> The `push() and pop() methods runs faster` than unshift() and shift(). Because push() and pop() methods add and remove elements at the end of an array, therefore, the elements do not move. unshift() and shift() add and remove elements at the beginning of the array that requires re-indexing/re-structuring of the whole array. > **Syntax & Example**: `11.08.01.script` + ```javascript // remove array element from start and end // myarray.pop(), myarray.shift() -var arrColors = new Array('Red', 'Green', 'Blue', 'Orange'); +var arrColors = new Array("Red", "Green", "Blue", "Orange"); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // remove an element from the end of the array arrColors.pop(); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); // ------------------------------ @@ -3006,13 +3064,13 @@ console.log('arrColors.length: ' + arrColors.length); let startElement = arrColors.shift(); console.log(startElement); console.log(arrColors); -console.log('arrColors.length: ' + arrColors.length); +console.log("arrColors.length: " + arrColors.length); ``` -11.09. Array properties and methods ---------------------- +## 11.09. Array properties and methods + +> **Syntax & Example**: `` -> **Syntax & Example**: `` ```javascript // length @@ -3059,32 +3117,29 @@ console.log(numberArray.find(40)); ``` -Section 12. Objects -===================== +# Section 12. Objects + +## 12.01. Real Life Objects -12.01. Real Life Objects ---------------------- -12.01. Object Properties and Method examples ---------------------- +## 12.01. Object Properties and Method examples -- In real life almost `everything is an object`. +- In real life almost `everything is an object`. - For example: Human, Car, Building, Bike, Pen, Chair, Monitor, Keyboard, Vehicle, Mobile, Computer etc. - Let's have a look on some Objects with Properties and Methods: -| Object | Properties | Methods | -|---------------|-----------------------------------------|------------------------------------| -| Person | Person.name = 'dinanath'; <br/> Person.weight = 65; <br/> Person.color = 'fair' | Person.walk(); <br/> Person.talk(); <br/> Person.eat(); | -| Bike | Bike.brand = 'bajaj'; <br/> Bike.model = 'discover'; <br/> Bike.color = 'blue'; <br/> Bike.length = 60; <br/> Bike.height = 30; <br/> | Bike.start(); <br/> Bike.break(); <br/> Bike.stop(); | -| Watch | Watch.type = 'analog'; <br/> Watch.price = 750; <br/> | Watch.showTime(); <br/> Watch.setAlarm(); | -| | | | +| Object | Properties | Methods | +| ------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| Person | Person.name = 'dinanath'; <br/> Person.weight = 65; <br/> Person.color = 'fair' | Person.walk(); <br/> Person.talk(); <br/> Person.eat(); | +| Bike | Bike.brand = 'bajaj'; <br/> Bike.model = 'discover'; <br/> Bike.color = 'blue'; <br/> Bike.length = 60; <br/> Bike.height = 30; <br/> | Bike.start(); <br/> Bike.break(); <br/> Bike.stop(); | +| Watch | Watch.type = 'analog'; <br/> Watch.price = 750; <br/> | Watch.showTime(); <br/> Watch.setAlarm(); | +| | | | > **Note**: <br/> -As a practice think of any other object in your surrounding and list down its Properties and Methods +> As a practice think of any other object in your surrounding and list down its Properties and Methods -12.02. What is an Object? ---------------------- -12.02. What are the Objects? ---------------------- +## 12.02. What is an Object? + +## 12.02. What are the Objects? - JavaScript is an `object-based language` and in JavaScript, almost everything is an object or acts like/as an object - An object is a `special/complex` data type that allows you to `store collections of data` @@ -3094,26 +3149,29 @@ As a practice think of any other object in your surrounding and list down its Pr - An object contains properties, defined as a `key-value pair` (Objects are a collection of `key-value pair`) - A property `key (name) is always a string`, but the value which it stores can be any data types, like strings, numbers, booleans, or complex data types like arrays, function and other objects - JavaScript object properties can be accessed through two methods: - 1. .DOT notation: `object.firstName` + 1. .DOT notation: `object.firstName` 2. []Bracket notation: `object['firstName']` ### Different ways to create/define an Object There are 3 main ways to construct an object: -1. By object literal + +1. By object literal 2. By creating an `instance` of Object directly (using `new` keyword) 3. By using an `Object constructor` (using `new` keyword) -12.03. Object literal ---------------------- + 12.03. Object literal + +--- - The simplest way to create an object in JavaScript is enclosing a `comma-separated list of properties:values and methods in curly braces { }` -- var MyObject = { property1: value1, property2: value2.....propertyN: valueN } +- var MyObject = { property1: value1, property2: value2.....propertyN: valueN } > **Syntax & Example**: + ```javascript // create object with object literal - + // var MyObject = { property1: value1, property2: value2.....propertyN: valueN } // empty object @@ -3121,64 +3179,69 @@ var HumanObj = {}; console.log(HumanObj); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // object with properties -var TechnologyObj = { 'name': 'JavaScript', 'version': 6, 'type': 'script', 'isStable': true } +var TechnologyObj = { + name: "JavaScript", + version: 6, + type: "script", + isStable: true, +}; console.log(TechnologyObj.name); -console.log(TechnologyObj['isStable']); +console.log(TechnologyObj["isStable"]); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // object properly alignment/arranged for readability - with quotes var VehicleObj1 = { - 'type': 'LWM', - 'brand': 'Maruti', - 'model': 'Alto-100', - 'color': 'White', - 'isHighEndModel': true, - 'price': 400000, + type: "LWM", + brand: "Maruti", + model: "Alto-100", + color: "White", + isHighEndModel: true, + price: 400000, keyStart: function () { - console.log(this.model + ' started!'); - } -} + console.log(this.model + " started!"); + }, +}; console.log(VehicleObj1.brand); -console.log(VehicleObj1['color']); +console.log(VehicleObj1["color"]); VehicleObj1.keyStart(); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // object properly alignment/arranged for readability - with quotes var VehicleObj2 = { - type: 'LWM', - brand: 'Maruti', - model: 'Alto-100', - color: 'White', + type: "LWM", + brand: "Maruti", + model: "Alto-100", + color: "White", isHighEndModel: true, price: 400000, keyStart: function () { - alert(this.model + 'started!'); - } -} + alert(this.model + "started!"); + }, +}; console.log(VehicleObj1.brand); -console.log(VehicleObj1['color']); +console.log(VehicleObj1["color"]); VehicleObj1.keyStart(); -console.log('// ------------------------------'); +console.log("// ------------------------------"); ``` -12.04. Creating an instance of Object directly ---------------------- -12.04. Creating an instance of object directly (using the new keyword) ---------------------- +## 12.04. Creating an instance of Object directly + +## 12.04. Creating an instance of object directly (using the new keyword) - Array instance can be created using the `new` keyword `new Array() with or without passing arguments/properties-methods` in constructor - var MyObject = new Object(); OR var MyObject = Object(); > **Syntax & Example**: + ```javascript // create object with new keyword @@ -3187,70 +3250,70 @@ console.log('// ------------------------------'); // object with properties var TechnologyObj = new Object(); -TechnologyObj.name = 'JavaScript'; +TechnologyObj.name = "JavaScript"; TechnologyObj.version = 6; -TechnologyObj.type = 'script'; -TechnologyObj.isStable = true +TechnologyObj.type = "script"; +TechnologyObj.isStable = true; console.log(TechnologyObj.name); -console.log(TechnologyObj['type']); +console.log(TechnologyObj["type"]); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // object properly alignment/arranged for readability - with quotes var VehicleObj1 = { - 'type': 'LWM', - 'brand': 'Maruti', - 'model': 'Alto-100', - 'color': 'red', - 'isHighEndModel': true, - 'price': 400000, + type: "LWM", + brand: "Maruti", + model: "Alto-100", + color: "red", + isHighEndModel: true, + price: 400000, keyStart: function () { - console.log(this.model + ' started!'); - } -} + console.log(this.model + " started!"); + }, +}; // access property with .DOT notation console.log(VehicleObj1.brand); // access property with []Bracket notation -console.log(VehicleObj1['color']); +console.log(VehicleObj1["color"]); VehicleObj1.keyStart(); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // object properly alignment/arranged for readability - without quotes var VehicleObj2 = { - type: 'LWM', - brand: 'Tata', - model: 'Safari', - color: 'White', + type: "LWM", + brand: "Tata", + model: "Safari", + color: "White", isHighEndModel: false, price: 1400000, keyStart: function () { - alert(this.model + 'started!'); - } -} + alert(this.model + "started!"); + }, +}; // access property with .DOT notation console.log(VehicleObj2.brand); // access property with []Bracket notation -console.log(VehicleObj2['color']); +console.log(VehicleObj2["color"]); VehicleObj1.keyStart(); -console.log('// ------------------------------'); +console.log("// ------------------------------"); ``` -12.05. Object constructor ---------------------- -12.05. Object constructor (using the new keyword) ---------------------- +## 12.05. Object constructor + +## 12.05. Object constructor (using the new keyword) -- In this method, create a function with arguments +- In this method, create a function with arguments - Each argument value can be assigned in the current object by using `this` keyword, `this` keyword refers to the `current object` -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // create an object with new keyword - Object constructor with function @@ -3262,122 +3325,122 @@ function Technology(name, version, type) { console.log(this.type); } -let JavaScript = new Technology('JavaScript', 6, 'Script Language'); +let JavaScript = new Technology("JavaScript", 6, "Script Language"); console.log(JavaScript.version); -console.log('// ------------------------------'); +console.log("// ------------------------------"); -function Vehicle(brand,model,color,price) { +function Vehicle(brand, model, color, price) { this.brand = brand; this.model = model; this.color = color; this.price = price; this.keyStart = function () { - console.log(this.model + ' started!'); - } + console.log(this.model + " started!"); + }; } -var Maruti = new Vehicle('Maruti','Alto-100','White',400000); +var Maruti = new Vehicle("Maruti", "Alto-100", "White", 400000); Maruti.keyStart(); -console.log('// ------------------------------'); +console.log("// ------------------------------"); ``` -12.06. Accessing objects properties ---------------------- -12.06. Looping through Objects properties ---------------------- +## 12.06. Accessing objects properties + +## 12.06. Looping through Objects properties - To access or get the value of a property, you can use the `dot .`, or `square bracket []` notation - We can iterate through the `key-value pairs` of an object using the `for...in loop` - MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName'] -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // access/loop thourgh array element // MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName'] var Person = { - name:'Dinanath', - domain:'IT/Software', - gender:'Male', - city:'Mumbai', - country:'India' -} + name: "Dinanath", + domain: "IT/Software", + gender: "Male", + city: "Mumbai", + country: "India", +}; console.log(Person.name); -console.log(Person['domain']); +console.log(Person["domain"]); -console.log('// ------------------------------'); +console.log("// ------------------------------"); // Loop through an Array Elements for (props in Person) { - console.log(Person[props]) + console.log(Person[props]); } -console.log('// ------------------------------'); +console.log("// ------------------------------"); ``` -12.07. Removing Deleting objects properties ---------------------- +## 12.07. Removing Deleting objects properties - The `delete` operator can be used to completely remove properties from an object - delete MyObject.propertyName; > **Note**: <br/> -The `delete` operator only removes an `object property or array element`. It does not work/does not affect variables or declared functions. +> The `delete` operator only removes an `object property or array element`. It does not work/does not affect variables or declared functions. + +> **Syntax & Example**: -> **Syntax & Example**: ```javascript // remove/delete Object's Properties // delete MyObject.propertyName; var Person = { - name:'Dinanath', - domain:'IT/Software', - gender:'Male', - city:'Mumbai', - country:'India' -} + name: "Dinanath", + domain: "IT/Software", + gender: "Male", + city: "Mumbai", + country: "India", +}; -delete Person.name +delete Person.name; console.log(Person); console.log(Person.name); -console.log(Person['domain']); +console.log(Person["domain"]); ``` -12.08. Manipulating by Value Vs Reference ---------------------- +## 12.08. Manipulating by Value Vs Reference In JavaScript we have two categories of types: + 1. Value Types (Primitives = Basic type) - Primitives are copied by their value 2. Reference Types (Objects = Complex type) - Objects are copied by their Reference/Location in memory ### 1. Value Types (Primitives) - 1. Number - 2. String - 3. Boolean - 4. Undefined - 5. Null - 6. Symbol (ES6) +1. Number +2. String +3. Boolean +4. Undefined +5. Null +6. Symbol (ES6) ### 2. Reference Types (Objects) - 1. Object - 2. Function - 3. Array +1. Object +2. Function +3. Array + +> **Syntax & Example**: -> **Syntax & Example**: ``` ??? ``` -12.09. The Window object ---------------------- +## 12.09. The Window object - Window Object the global variable/global object `available in the browser environment`, represents the browser window in which the script is running - Simply, the window object `represents a window in a browser` @@ -3386,23 +3449,22 @@ In JavaScript we have two categories of types: - The Browser Object Model (BOM) allows JavaScript to "communicate/talk to" the browser - In `Browser -> Inspect Element -> Console Panel` -> Type `Window`, check different properties and methods available -> **Syntax & Example**: -```javascript +> **Syntax & Example**: +```javascript // Methods -window.console.log('Console! Hello, Welcome to JavaScript'); +window.console.log("Console! Hello, Welcome to JavaScript"); -window.alert('Alert! Hello, Welcome to JavaScript'); +window.alert("Alert! Hello, Welcome to JavaScript"); // const namePrompt = window.prompt(); -const namePrompt = window.prompt('Enter Your Name'); +const namePrompt = window.prompt("Enter Your Name"); window.alert(namePrompt); - -if(window.confirm('Are you sure?')) { - window.console.log('YES - selected'); +if (window.confirm("Are you sure?")) { + window.console.log("YES - selected"); } else { - window.console.log('NO - clicked'); + window.console.log("NO - clicked"); } // Properties @@ -3411,28 +3473,28 @@ if(window.confirm('Are you sure?')) { outerHeight = window.outerHeight; outerWidth = window.outerWidth; -console.log('outerHeight -', outerHeight, '::', 'outerWidth -', outerWidth ); +console.log("outerHeight -", outerHeight, "::", "outerWidth -", outerWidth); // document/page height & width innerHeight = window.innerHeight; innerWidth = window.innerWidth; -console.log('innerHeight -', innerHeight, '::', 'innerWidth -', innerWidth ); +console.log("innerHeight -", innerHeight, "::", "innerWidth -", innerWidth); // scroll position -console.log('scrollY', window.scrollY); -console.log('scrollX', window.scrollX); +console.log("scrollY", window.scrollY); +console.log("scrollX", window.scrollX); -// location +// location -console.log('current window location/url', window.location); -console.log('current window location/url', window.location.href); +console.log("current window location/url", window.location); +console.log("current window location/url", window.location.href); // location redirect -window.location.href = 'https://www.google.com'; +window.location.href = "https://www.google.com"; // window location/visited history @@ -3442,22 +3504,20 @@ let totalPagesVisitedHistory = window.history.length; // current browser details - navigator -let curBrowser = window.navigator.appName; +let curBrowser = window.navigator.appName; //window.navigator.userAgent; window.navigator.platform; window.navigator.vendor; - ``` -12.10. The Math Object ---------------------- +## 12.10. The Math Object - The Math object allows to perform mathematical tasks -- Math object provides several constants and methods to perform mathematical operation (like `min, max, sqrt, pi, round, random`, etc) +- Math object provides several constants and methods to perform mathematical operation (like `min, max, sqrt, pi, round, random`, etc) -> **Syntax & Example**: -```javascript +> **Syntax & Example**: +```javascript let pieValue = Math.PI; console.log(Math.E); @@ -3469,8 +3529,8 @@ console.log(Math.floor(2.6)); console.log(Math.sqrt(64)); console.log(Math.abs(-10)); //return absolute ie positive number -console.log(Math.pow(8,2)); //64 -console.log(Math.pow(10,3)); //10 * 10 * 10 = 1000 +console.log(Math.pow(8, 2)); //64 +console.log(Math.pow(10, 3)); //10 * 10 * 10 = 1000 console.log(Math.min(20, 5, 9, 15, 2)); console.log(Math.max(20, 5, 9, 15, 2)); @@ -3478,24 +3538,22 @@ console.log(Math.max(20, 5, 9, 15, 2)); console.log(Math.random()); console.log(Math.random() * 20 + 1); // random number till 20 console.log(Math.floor(Math.random() * 20 + 1)); // random number till 20 without any decimals - ``` -12.11. Date and Time -===================== +# 12.11. Date and Time - The Date object is used to deal/work with date and time - Simply, the JavaScript date object can be used to get date, day, month and year - Date objects are created with `new Date()` - Date constructor can be used to create date object, It provides methods to get and set day, month, year, hour, minute and seconds -> **Syntax & Example**: -```javascript +> **Syntax & Example**: +```javascript const today = new Date(); -console.log('today is:', today); +console.log("today is:", today); -const date1 = new Date('March 29 1980'); -const date2 = new Date('09-10-1980'); +const date1 = new Date("March 29 1980"); +const date2 = new Date("09-10-1980"); let currentDate = new Date(); @@ -3508,24 +3566,23 @@ const currentMinutes = currentDate.getMinutes(); const newBirthDate = currentDate.setMonth(5); console.log(newBirthDate); - ``` -Section 13. Events -===================== +# Section 13. Events -13.01. Understanding Events and Event Handlers ---------------------- +## 13.01. Understanding Events and Event Handlers - Events are happening/triggering all over, Event lets the developer know `something has occurred/happened` - Events occur when the page loads (Onload), when the user interacts with the web page (clicked a link or button/hover) (onlick), pressed key, moved the mouse pointer, mouse-clicked/hover (onmouseover), entered text into an input box or textarea (onchange, onblur, onfocus), submits a form (submit), page unloads (unload) - When an event occurs, use a JavaScript `event handler (or an event listener) to detect` them and perform a specific task - Event handlers name always begin with the word `"on"`, like onclick, onload, onblur, and so on - To react to an event you `listen` for it and supply a `callback function or event handler` which will be called by the browser when the event occurs -13.02. Different Event category ---------------------- + 13.02. Different Event category + +--- In general, the events can be categorized into four main groups: + 1. Mouse events 2. Keyboard events 3. Form events @@ -3536,58 +3593,89 @@ In general, the events can be categorized into four main groups: A mouse event is triggered when the user clicks some element, move the mouse pointer over an element, etc. Find here some of the important mouse events and their event handler: - **click** (`onclick` event handler) - - Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page + - Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page - **contextmenu** (`oncontextmenu` event handler) - Occurs when a `user clicks the right mouse button` on an element to open a context menu -- **mouseover / mouseout** (`onmouseover` & `onmouseout` event handler) +- **mouseover / mouseout** (`onmouseover` & `onmouseout` event handler) - Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element - **mousedown / mouseup** (`onclick/onmousedown` & `onmouseup`) - Occurs when the mouse button is pressed/released over an element - **mousemove** (`onmousemove` event handler) - Occurs when the mouse pointer/cursor is moved -> **Syntax & Example**: +> **Syntax & Example**: + ```html <ol class="normalList"> - <li><strong>click</strong> (`onclick` event handler) <br/> - <span onclick="alert('You have clicked an element!')" style="color:blue;cursor: pointer;">Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page </span> + <li> + <strong>click</strong> (`onclick` event handler) <br /> + <span + onclick="alert('You have clicked an element!')" + style="color:blue;cursor: pointer;" + >Occurs When the `mouse clicks on an element`, links, buttons etc. on a + web page + </span> </li> - <li><strong>contextmenu</strong> (`oncontextmenu` event handler) <br/> - <span oncontextmenu="alert('You have Right clicked on Me!')" style="color:blue;cursor: pointer;">Occurs when a `user clicks the right mouse button` on an element to open a context menu</span> + <li> + <strong>contextmenu</strong> (`oncontextmenu` event handler) <br /> + <span + oncontextmenu="alert('You have Right clicked on Me!')" + style="color:blue;cursor: pointer;" + >Occurs when a `user clicks the right mouse button` on an element to open + a context menu</span + > </li> - <li><strong>mouseover / mouseout</strong> (`onmouseover` & `onmouseout` event handler) <br/> - <span onmouseover="console.log('You have Mouse Over Me!')" onmouseout="console.log('You have Mouse Out Me!')" style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element</span> + <li> + <strong>mouseover / mouseout</strong> (`onmouseover` & `onmouseout` event + handler) <br /> + <span + onmouseover="console.log('You have Mouse Over Me!')" + onmouseout="console.log('You have Mouse Out Me!')" + style="color:blue;cursor: pointer;" + >Occurs when the mouse pointer/cursor comes over / leaves (goes outside + of) an element</span + > </li> - <li><strong>mousedown / mouseup</strong> (`onclick/onmousedown` & `onmouseup`) <br/> - <span onmousedown="console.log('You have clicked on Me!')" onmouseup="console.log('You have released click on Me!')"style="color:blue;cursor: pointer;">Occurs when the mouse button is pressed / released over an element</span> + <li> + <strong>mousedown / mouseup</strong> (`onclick/onmousedown` & `onmouseup`) + <br /> + <span + onmousedown="console.log('You have clicked on Me!')" + onmouseup="console.log('You have released click on Me!')" + style="color:blue;cursor: pointer;" + >Occurs when the mouse button is pressed / released over an element</span + > </li> - <li><strong>mousemove</strong> (`onmousemove` event handler) <br/> - <span onmousemove="console.log('You Moved mouse over Me!')" style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor is moved</span> + <li> + <strong>mousemove</strong> (`onmousemove` event handler) <br /> + <span + onmousemove="console.log('You Moved mouse over Me!')" + style="color:blue;cursor: pointer;" + >Occurs when the mouse pointer/cursor is moved</span + > </li> </ol> - ``` <hr/> > **Syntax & Example**: `Change background color on mouse movement` -```js -const button = document.querySelector('.some-button'); -const headingText = document.querySelector('h1'); +```js +const button = document.querySelector(".some-button"); +const headingText = document.querySelector("h1"); -button.addEventListener('mousemove', someFunction); +button.addEventListener("mousemove", someFunction); function someFunction(evt) { - console.log('Event Details:', evt); - headingText.innerText = 'Changed after click!'; + console.log("Event Details:", evt); + headingText.innerText = "Changed after click!"; - document.body.style.backgroundColor = `rgb(${evt.offsetX},${evt.offsetY},40)` + document.body.style.backgroundColor = `rgb(${evt.offsetX},${evt.offsetY},40)`; } - ``` -### 13.02.02. Keyboard events +### 13.02.02. Keyboard events A keyboard event is fired up when the user presses or release a key on the keyboard. Here're some of the important keyboard events and their event handler: @@ -3597,29 +3685,32 @@ A keyboard event is fired up when the user presses or release a key on the keybo - Occurs when the user presses down a key on the keyboard that has a character value associated with it - Keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc. will not generate a keypress event, but will generate a keydown and keyup event -> **Syntax & Example**: -```html -<label>Enter Name:</label> +> **Syntax & Example**: -<input type="text" placeholder="Enter Name" -onkeydown="console.log('onkeydown pressed a key inside input text!')" -onkeyup="console.log('onkeyup released a key inside input text!')" -onkeypress="console.log('onkeypress Other than Ctrl, Shift, Alt, Esc, Arrow keys pressed!')"/> +```html +<label>Enter Name:</label> + +<input + type="text" + placeholder="Enter Name" + onkeydown="console.log('onkeydown pressed a key inside input text!')" + onkeyup="console.log('onkeyup released a key inside input text!')" + onkeypress="console.log('onkeypress Other than Ctrl, Shift, Alt, Esc, Arrow keys pressed!')" +/> ``` <hr/> -> **Syntax & Example**: -```js +> **Syntax & Example**: -const nameText = document.querySelector('inputNameText'); -nameText.addEventListener('keypress', nameData); +```js +const nameText = document.querySelector("inputNameText"); +nameText.addEventListener("keypress", nameData); function nameData(evt) { - console.log('nameData function called'); + console.log("nameData function called"); headingText.innerText = evt.target.value; } - ``` ### 13.02.03. Form events @@ -3635,26 +3726,37 @@ A form event is triggered when a form control/form fields (text fields/radio but - **submit** (`onsubmit` event handler) - Occurs only when the user submits a form on a web page -> **Syntax & Example**: -```html -<form action="" method="post" onsubmit="alert('Form data submitted to the server!');"> +> **Syntax & Example**: +```html +<form + action="" + method="post" + onsubmit="alert('Form data submitted to the server!');" +> <label>First Name:</label> - <input type="text" name="first-name" onfocus="showHighlight(this)" onblur="resetHighlight(this)" required> <br/> <br/> + <input + type="text" + name="first-name" + onfocus="showHighlight(this)" + onblur="resetHighlight(this)" + required + /> + <br /> + <br /> <select onchange="console.log('You have selected something!');"> - <option>Select</option> - <option>Male</option> - <option>Female</option> - </select> <br/> <br/> - - <input type="submit" value="Submit"> - + <option>Select</option> + <option>Male</option> + <option>Female</option> + </select> + <br /> + <br /> + + <input type="submit" value="Submit" /> </form> - <script> - // focus text field function showHighlight(curTxtField) { curTxtField.style.background = "pink"; @@ -3663,25 +3765,22 @@ A form event is triggered when a form control/form fields (text fields/radio but function resetHighlight(curTxtField) { curTxtField.style.background = "white"; } - </script> - ``` <hr/> > **Syntax & Example**: `Form submit event` -```js -const personalDataForm = document.querySelector('form'); -personalDataForm.addEventListener('submit', submitData); +```js +const personalDataForm = document.querySelector("form"); +personalDataForm.addEventListener("submit", submitData); function submitData(evt) { - console.log('submitData function called'); + console.log("submitData function called"); // to prevent the default behavior of an element - button, link, submit button etc. evt.preventDefault(); } - ``` ### 13.02.04. Document/Window events @@ -3698,28 +3797,28 @@ Events are happening/triggering all over. Events do trigger even when the page h - Occurs when a user resizes the browser window, even when browser window minimized or maximized > **Note**: <br/> -The unload event is not supported properly in most of the browsers. - -> **Syntax & Example**: -```html -<body onload="window.alert('Page loaded successfully!');" onunload="window.alert('sure you want to leave this page?');"> +> The unload event is not supported properly in most of the browsers. +> **Syntax & Example**: -<script> - - // resize window - window.onresize = resizeWindowSize; - - function resizeWindowSize() { - console.log('window.outerWidth ' + window.outerWidth); - console.log('window.outerHeight ' + window.outerHeight); - } - -</script> +```html +<body + onload="window.alert('Page loaded successfully!');" + onunload="window.alert('sure you want to leave this page?');" +> + <script> + // resize window + window.onresize = resizeWindowSize; + + function resizeWindowSize() { + console.log("window.outerWidth " + window.outerWidth); + console.log("window.outerHeight " + window.outerHeight); + } + </script> +</body> ``` -13.03. Different ways to write the event handler ---------------------- +## 13.03. Different ways to write the event handler 1. HTML Attribute 2. DOM element properties (anonymous function) @@ -3727,7 +3826,8 @@ The unload event is not supported properly in most of the browsers. #### 13.03.01. HTML attribute -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript <h2 onclick="window.alert('HTML attribute onclick used here!')" style="color:#0000ff; cursor:pointer"> 13.03.01. HTML attribute | Click Me!</h2> @@ -3745,11 +3845,12 @@ function fnShowMessage () { ``` > **Note**: <br/> -This way should be avoided as it makes markup less readable and making it harder to find if there is any bug. +> This way should be avoided as it makes markup less readable and making it harder to find if there is any bug. #### 13.03.02. DOM element properties -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript <button id="messageButton1">Click here...</button> <button id="messageButton2">Click here...</button> @@ -3773,19 +3874,21 @@ function fnShowMessage() { #### 13.03.03. Registering event listeners -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // myButton.addEventListener('click', someFunc, false); -document.querySelector('.clear-button').addEventLister('click', function() { - console.log('clear-button clicked'); -}) +document.querySelector(".clear-button").addEventLister("click", function () { + console.log("clear-button clicked"); +}); ``` > **Note**: <br/> -This method is preferred in modern web pages. IE 6-8 do not support this method, there is an alternate for the `addEventListener` is `attachEvent` (myButton.attachEvent (‘onclick', someFunc);) +> This method is preferred in modern web pages. IE 6-8 do not support this method, there is an alternate for the `addEventListener` is `attachEvent` (myButton.attachEvent (‘onclick', someFunc);) + +> **Syntax & Example**: -> **Syntax & Example**: ```javascript ??? @@ -3798,49 +3901,45 @@ This method is preferred in modern web pages. IE 6-8 do not support this method, - Event Delegation = Event Delegation is exactly the opposite of Event Bubbling. It simply means event passed from top to bottom ie from parent to child element ```html - -// create an example of nested element - -??? - +// create an example of nested element ??? ``` -Section 14. DOM (Document Object Model) -===================== +# Section 14. DOM (Document Object Model) -14.01. What is DOM? ---------------------- -14.01. What is the Document Object Model? ---------------------- +## 14.01. What is DOM? + +## 14.01. What is the Document Object Model? - DOM represents the whole HTML document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way - The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings, etc.), are related to the topmost structure: the document itself -- DOM defines the logical structure of the documents and how they can be accessed and manipulated +- DOM defines the logical structure of the documents and how they can be accessed and manipulated - DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content - In DOM world always think in form/terms of `Nodes` (elements, its attributes, text, etc.) * Structural representation of HTML document (Tree of nodes/elements/tags) -14.02. Node ---------------------- + 14.02. Node + +--- As we learned above, in DOM, all parts of the document (like elements, its attributes, text, etc.) are organized in a hierarchical tree-like structure; similar to a real-life family tree that consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. There are different types of nodes like: `Elements, Attribute & Text Node`. -> **Syntax & Example**: -```html +> **Syntax & Example**: -<ul id="list"> --> Element & Attribute NODE - <li>first item </li> --> text NODE +```html +<ul id="list"> + --> Element & Attribute NODE + <li>first item</li> + --> text NODE </ul> * Elements NODES does not contain text - ``` -> **Syntax & Example**: -`In Browser Window -> Inspect Element (Developer Tools) -> Console: type following and check the output thoroughly` +> **Syntax & Example**: +> `In Browser Window -> Inspect Element (Developer Tools) -> Console: type following and check the output thoroughly` - `document` - outputs the entire document/current page @@ -3852,8 +3951,7 @@ There are different types of nodes like: `Elements, Attribute & Text Node`. HTMLAllCollection(1532) [html, head, meta, link, link, link, link, link, link, link, link, link, meta, title, meta, link, link, meta, meta, meta, meta, meta, meta, meta, meta, meta, ``` -14.03. JavaScript DOM Selectors ---------------------- +## 14.03. JavaScript DOM Selectors JavaScript is commonly used to find or select, to get or modify the content/value of the HTML elements on the page, and as well as to apply some effects (like show, hide, add events, animate, etc.) @@ -3867,34 +3965,35 @@ Let's learn some of the common ways of selecting the elements on a page and do s - `getElementById()` is the easiest and most common way to find/access an HTML element in the DOM tree - `getElementById()` method returns the element having the given id value -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); // get html of selected element let mainHeadingHtml = mainHeadingElement.innerHTML; // get text of selected element let mainHeadingText = mainHeadingElement.innerText; -alert('mainHeadingHtml: ' + mainHeadingHtml); // text with complete html tags -alert('mainHeadingText: ' + mainHeadingText); // only text +alert("mainHeadingHtml: " + mainHeadingHtml); // text with complete html tags +alert("mainHeadingText: " + mainHeadingText); // only text // console.log('// ------------------------------'); // set text of selected element -mainHeadingElement.innerHTML = 'This text changed with DOM method...'; +mainHeadingElement.innerHTML = "This text changed with DOM method..."; // console.log('// ------------------------------'); // set text of another element -let subHeadingElement = document.getElementById('subHeadingText'); -subHeadingElement.innerHTML = mainHeadingElement.innerHTML ; +let subHeadingElement = document.getElementById("subHeadingText"); +subHeadingElement.innerHTML = mainHeadingElement.innerHTML; // console.log('// ------------------------------'); // set css style -mainHeadingElement.style.backgroundColor = 'pink'; +mainHeadingElement.style.backgroundColor = "pink"; ``` ### 14.03.02. Selecting Elements by Class Name (`getElementsByClassName()`) @@ -3902,7 +4001,8 @@ mainHeadingElement.style.backgroundColor = 'pink'; - `getElementsByClassName()` method is used to select all the `elements having specific class names` - `getElementsByClassName()` method `returns an array of all elements` with given class names -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // Selecting elements with class let listItems = document.getElementsByClassName("list-item"); @@ -3910,20 +4010,20 @@ console.log(listItems); // get text of 1st ie 0th element let firstListItemText = listItems[0].innerHTML; -console.log('firstListItemText: ' + firstListItemText); +console.log("firstListItemText: " + firstListItemText); // console.log('// ------------------------------'); // set text of last element -let lastListItem = (listItems.length - 1); -listItems[lastListItem].style.color = 'blue'; +let lastListItem = listItems.length - 1; +listItems[lastListItem].style.color = "blue"; // console.log('// ------------------------------'); // highlighting all list items through loop -for(var listItem in listItems) { - listItems[listItem].style.marginBottom = '10px'; - listItems[listItem].style.background = '#bbbbbb'; +for (var listItem in listItems) { + listItems[listItem].style.marginBottom = "10px"; + listItems[listItem].style.background = "#bbbbbb"; } ``` @@ -3932,10 +4032,11 @@ for(var listItem in listItems) { - Developer can also `select HTML elements by tag name` using the `getElementsByTagName()` method - `getElementsByTagName()` method `returns an array of all elements` with given tag name -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // Selecting all LI elements with tag name -let liElements = document.getElementsByTagName('li'); +let liElements = document.getElementsByTagName("li"); console.log(liElements); // console.log('// ------------------------------'); @@ -3948,20 +4049,20 @@ console.log(totalLiElements); // get text of 1st ie 0th li element let firstLiText = liElements[0].innerHTML; -console.log('firstLiText: ' + firstLiText); +console.log("firstLiText: " + firstLiText); // console.log('// ------------------------------'); // set text of last element -let lastLi = (liElements.length - 1); -liElements[lastLi].style.color = 'blue'; +let lastLi = liElements.length - 1; +liElements[lastLi].style.color = "blue"; // console.log('// ------------------------------'); // highlighting all li elements through loop -for(var li in liElements) { - liElements[li].style.marginBottom = '10px'; - liElements[li].style.background = '#bbbbbb'; +for (var li in liElements) { + liElements[li].style.marginBottom = "10px"; + liElements[li].style.background = "#bbbbbb"; } // console.log('// ------------------------------'); @@ -3973,23 +4074,25 @@ for(var li in liElements) { - CSS selectors provide a very `powerful and efficient way` of selecting HTML elements in a document - `querySelectorAll()` method `returns an array` or list of all the elements that matches the specified selectors -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript // Selecting all ul -> li elements -let ulLiElement = document.querySelectorAll('ul li'); +let ulLiElement = document.querySelectorAll("ul li"); console.log(ulLiElement); -let ulListItemClass = document.querySelectorAll("ul li.list-item") +let ulListItemClass = document.querySelectorAll("ul li.list-item"); console.log(ulListItemClass); // set color of last li element -ulLiElement[ulLiElement.length - 1].style.color = 'red'; +ulLiElement[ulLiElement.length - 1].style.color = "red"; // set text of last li element -ulLiElement[ulLiElement.length - 1].innerHTML = 'Dynamic text change at run time'; +ulLiElement[ulLiElement.length - 1].innerHTML = + "Dynamic text change at run time"; ``` -### 14.03.05. `querySelector` +### 14.03.05. `querySelector` - selects the single ie first element @@ -3999,110 +4102,123 @@ ulLiElement[ulLiElement.length - 1].innerHTML = 'Dynamic text change at run time ``` -14.04. JavaScript DOM CSS Styling ---------------------- +## 14.04. JavaScript DOM CSS Styling Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time. We can apply/set almost all the CSS styles for the elements like fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. ### Naming Conventions of CSS Properties in JavaScript + - CSS properties like `font-size`, `background-image`, `text-decoration`, etc. contain `hyphens (-)` in names - In JavaScript `hyphens (-)` is a reserved operator (a minus sign), so it is impossible to write an expression with `hyphens (-)`, like: elem.style.font-size = '10px'; - In JavaScript the CSS property names with hyphens are converted to intercapitalized style word (camelCasingNaming) - So CSS property `font-size`, `background-color`,`border-left-style` becomes the DOM property `fontSize`, `borderLeftStyle` respectively and so on ### 14.04.01. Applying/Setting Inline Styles on Elements + - In HTML inline styles are applied directly to the specific HTML element using the `style attribute`, eg. `<element style="color:red;">` - In JavaScript the `style property` is used to get or set the inline style of an element, eg. `elem.style.color = 'red';` -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); // set css style -mainHeadingElement.style.padding = '5px'; -mainHeadingElement.style.backgroundColor = 'pink'; -mainHeadingElement.style.color = 'blue'; -mainHeadingElement.style.border = '5px solid #999999'; +mainHeadingElement.style.padding = "5px"; +mainHeadingElement.style.backgroundColor = "pink"; +mainHeadingElement.style.color = "blue"; +mainHeadingElement.style.border = "5px solid #999999"; ``` ### 14.04.02. Retrieving/Getting CSS Styles details from Elements + - We can get the styles applied on the HTML elements using the `style property` - `style property` only returns the style rules set in the element's style attribute, not those applied through internal/embedded style sheets, or external style sheets - To get the values of all CSS properties that actually render an element we can use the `window.getComputedStyle()` method -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); // set css style -mainHeadingElement.style.padding = '5px'; -mainHeadingElement.style.backgroundColor = 'pink'; +mainHeadingElement.style.padding = "5px"; +mainHeadingElement.style.backgroundColor = "pink"; // console.log('// ------------------------------'); // get inline css styles -console.log('mainHeadingElement.style.padding:',mainHeadingElement.style.padding); -console.log('mainHeadingElement.style.backgroundColor:',mainHeadingElement.style.backgroundColor); +console.log( + "mainHeadingElement.style.padding:", + mainHeadingElement.style.padding +); +console.log( + "mainHeadingElement.style.backgroundColor:", + mainHeadingElement.style.backgroundColor +); // console.log('// ------------------------------'); // get computed style information/ any type of css styles internal/embeded style sheets var cssStyles = window.getComputedStyle(mainHeadingElement); -console.log('internal style - color:',cssStyles.color); -console.log('internal style - border:',cssStyles.border); +console.log("internal style - color:", cssStyles.color); +console.log("internal style - border:", cssStyles.border); ``` ### 14.04.03. Applying/Adding CSS Classes to Elements - className + - We can also get or set CSS classes to the HTML elements using the `className property` - As `class` is a reserved word in JavaScript, it uses the `className` property to reference the value of the HTML class attribute -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); // remove old classes and apply/set css class -mainHeadingElement.className = 'bg-color'; +mainHeadingElement.className = "bg-color"; // apply/set css class -mainHeadingElement.className += ' border'; +mainHeadingElement.className += " border"; ``` ### 14.04.04. Applying/Adding CSS Classes to Elements - classList + - Using `classList property` is much easier and better to get, set or remove CSS classes from an element - `classList property` is supported in all major browsers except Internet Explorer before version 10 -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); // apply/set/add css class with classList -mainHeadingElement.classList.add('heading-text'); +mainHeadingElement.classList.add("heading-text"); // apply/set/add css class with classList -mainHeadingElement.classList.add('border','bg-color'); +mainHeadingElement.classList.add("border", "bg-color"); // remove classes with classList -mainHeadingElement.classList.remove('border','bg-color'); +mainHeadingElement.classList.remove("border", "bg-color"); // if class exists remove it, if not add it -mainHeadingElement.classList.toggle('heading-text'); +mainHeadingElement.classList.toggle("heading-text"); // mainHeadingElement.classList.add('border'); // check if class exist and act accordingly -if(mainHeadingElement.classList.contains('border')) { - alert('border class present'); +if (mainHeadingElement.classList.contains("border")) { + alert("border class present"); } else { - alert('NO border class present'); + alert("NO border class present"); } ``` -14.05. JavaScript DOM HTML get set attributes ---------------------- +## 14.05. JavaScript DOM HTML get set attributes - An attribute in HTML `provides extra information` about the element, and it is applied within the start tag - An HTML attribute contains two fields: `name & value / key & value` @@ -4113,21 +4229,22 @@ if(mainHeadingElement.classList.contains('border')) { - The `setAttribute()` method is used to set an attribute on the specified element - If the attribute already present/exists on the element, the attribute value will be updated; else a new attribute is added with the specified name and value -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); +let clickButtonElement = document.getElementById("clickButton"); +let linkTextElement = document.getElementById("linkText"); // set attribute class named 'btn' -mainHeadingElement.setAttribute('class', 'btn'); +mainHeadingElement.setAttribute("class", "btn"); // set attribute disabled -clickButtonElement.setAttribute('disabled', ''); +clickButtonElement.setAttribute("disabled", ""); // set blank/empty attribute so that it will remove exisiting attribute value -linkTextElement.setAttribute('href',''); +linkTextElement.setAttribute("href", ""); ``` ### 14.05.02. Retrieving/Getting Attribute Value @@ -4135,53 +4252,63 @@ linkTextElement.setAttribute('href',''); - The `getAttribute()` method is used to get the current value of an attribute on the element - If the specified attribute does not present/exists on the element, it will return `null` -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); +let clickButtonElement = document.getElementById("clickButton"); +let linkTextElement = document.getElementById("linkText"); // getting the attributes values -let getAttrClass = mainHeadingElement.getAttribute('class'); -console.log('getAttrClass:', getAttrClass); +let getAttrClass = mainHeadingElement.getAttribute("class"); +console.log("getAttrClass:", getAttrClass); -let getAttrDisabled = clickButtonElement.getAttribute('disabled'); -console.log('getAttrDisabled:', getAttrDisabled); +let getAttrDisabled = clickButtonElement.getAttribute("disabled"); +console.log("getAttrDisabled:", getAttrDisabled); -let getAttrHref = linkTextElement.getAttribute('href'); -console.log('getAttrHref:', getAttrHref); +let getAttrHref = linkTextElement.getAttribute("href"); +console.log("getAttrHref:", getAttrHref); ``` ### 14.05.03. Removing Attributes from Elements - The `removeAttribute()` method is used to remove an attribute from the specified element -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); +// Selecting element with id +let mainHeadingElement = document.getElementById("mainHeadingText"); +let clickButtonElement = document.getElementById("clickButton"); +let linkTextElement = document.getElementById("linkText"); -// removing the attributes -mainHeadingElement.removeAttribute('class'); +// removing the attributes +mainHeadingElement.removeAttribute("class"); // verify/confirm class removed or not -console.log('mainHeadingElement.getAttribute:', mainHeadingElement.getAttribute('class')); -console.log('mainHeadingElement.classList.contains:', mainHeadingElement.classList.contains('class')); +console.log( + "mainHeadingElement.getAttribute:", + mainHeadingElement.getAttribute("class") +); +console.log( + "mainHeadingElement.classList.contains:", + mainHeadingElement.classList.contains("class") +); // console.log('// ------------------------------'); -clickButtonElement.removeAttribute('disabled'); +clickButtonElement.removeAttribute("disabled"); -linkTextElement.removeAttribute('href'); +linkTextElement.removeAttribute("href"); ``` ### 14.05.04. Selecting document elements without selectors + ### 14.05.04. Select HTMLCollection without selectors -> **Syntax & Example**: +> **Syntax & Example**: + ```javascript - document.forms @@ -4204,18 +4331,224 @@ linkTextElement.removeAttribute('href'); ``` -Section 15. What's Next Step? -===================== -Great Job! Thank You for looking into JavaScript for Beginners. I hope you enjoyed and learned a lot out of it. I think Now you have better understandings of how JavaScript works and functions. To learn more about JavaScript visit [Mozilla JavaScript Reference Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript). -- Your Next step could be looking into advanced topics of [HTML5](https://github.com/dinanathsj29/html5-semantic-tags), [CSS3] or [JavaScript]. +# Section 15. DOM (Advanced): + +## 15.01. Dynamic DOM Manipulation + +Dynamic DOM manipulation refers to creating, adding, modifying, and removing HTML elements on a web page programmatically using JavaScript. This makes web applications interactive and responsive to user inputs or actions. + +### 15.01.01. Creating and Appending Elements + +You can create new HTML elements dynamically using the `document.createElement()` method and append them to the DOM using methods like `appendChild()` or `append()`. + +> **Syntax & Example:** + +```javascript +// Create a new element +let newParagraph = document.createElement("p"); + +// Add text content to the new element +newParagraph.innerText = "This is a dynamically created paragraph."; + +// Append the new element to an existing parent element +let parentElement = document.getElementById("content"); +parentElement.appendChild(newParagraph); + +// Alternative: Use append() for modern browsers +let newSpan = document.createElement("span"); +newSpan.innerText = " Appended using append()."; +parentElement.append(newSpan); +``` + +### 15.01.02. Removing Elements + +Elements can be removed using `removeChild()` or the more modern `remove()` method. + +> **Syntax & Example:** + +```javascript +// Select the element to be removed +let elementToRemove = document.getElementById("oldItem"); + +// Remove the element using removeChild() +let parentElement = elementToRemove.parentElement; +parentElement.removeChild(elementToRemove); + +// Alternative: Use remove() for modern browsers +let anotherElementToRemove = document.getElementById("unusedItem"); +anotherElementToRemove.remove(); +``` + +### 15.01.03. Replacing Elements + +Replace an existing DOM element with another using the `replaceChild()` method. + +> **Syntax & Example:** + +```javascript +// Create a new element +let replacementElement = document.createElement("h2"); +replacementElement.innerText = "This is the replacement element."; + +// Select the element to replace +let oldElement = document.getElementById("replaceMe"); + +// Replace the old element +let parentElement = oldElement.parentElement; +parentElement.replaceChild(replacementElement, oldElement); +``` + +--- + +## 15.02. Class Manipulation + +Class manipulation allows you to add, remove, or toggle CSS classes dynamically, which is useful for applying or changing styles on the fly. + +### 15.02.01. Adding Classes: `classList.add()` + +Add one or more classes to an element. + +> **Syntax & Example:** + +```javascript +let element = document.getElementById("box"); +element.classList.add("highlight", "rounded"); +``` + +### 15.02.02. Removing Classes: `classList.remove()` + +Remove one or more classes from an element. + +> **Syntax & Example:** + +```javascript +let element = document.getElementById("box"); +element.classList.remove("highlight", "rounded"); +``` + +### 15.02.02. Toggling Classes: `classList.toggle()` + +Toggle a class on an element. If the class exists, it will be removed; if it does not exist, it will be added. + +> **Syntax & Example:** + +```javascript +let element = document.getElementById("box"); + +// Toggle a single class +element.classList.toggle("active"); + +// Toggle a class with a force parameter +let isForceAdded = element.classList.toggle("active", true); // Always add +let isForceRemoved = element.classList.toggle("active", false); // Always remove +``` + +### 15.02.03. Checking Class Existence: `classList.contains()` + +Check if an element contains a specific class. + +> **Syntax & Example:** + +```javascript +let element = document.getElementById("box"); +if (element.classList.contains("highlight")) { + console.log("The highlight class is present."); +} else { + console.log("The highlight class is not present."); +} +``` + +--- + +## 15.03. Handling Forms and Input Fields + +### 15.03.01. Form Validation + +Form validation ensures that user inputs are correct and complete before submitting the form. JavaScript can perform both client-side and custom validations. + +> **Example: Simple Form Validation** + +```html +<form id="registrationForm"> + <label for="username">Username:</label> + <input type="text" id="username" name="username" required /> + + <label for="email">Email:</label> + <input type="email" id="email" name="email" required /> + + <button type="submit">Register</button> +</form> + +<script> + // Select the form + let form = document.getElementById("registrationForm"); + + // Add submit event listener + form.addEventListener("submit", function (event) { + let username = document.getElementById("username").value; + let email = document.getElementById("email").value; + + // Custom validation + if (username.trim() === "") { + alert("Username cannot be empty!"); + event.preventDefault(); // Prevent form submission + } else if (!validateEmail(email)) { + alert("Invalid email address!"); + event.preventDefault(); + } + }); + + // Helper function to validate email + function validateEmail(email) { + let regex = /^[\w-.]+@[\w-]+\.[a-z]{2,7}$/i; + return regex.test(email); + } +</script> +``` + +### 15.02.02. Dynamic Input Field Manipulation + +You can dynamically add or remove input fields based on user interactions. + +> **Example:** + +```javascript +let addButton = document.getElementById("addInput"); +let container = document.getElementById("inputContainer"); + +// Add new input field +addButton.addEventListener("click", function () { + let newInput = document.createElement("input"); + newInput.type = "text"; + newInput.name = "dynamicInput"; + container.appendChild(newInput); +}); + +// Remove the last input field +let removeButton = document.getElementById("removeInput"); +removeButton.addEventListener("click", function () { + if (container.lastChild) { + container.removeChild(container.lastChild); + } +}); +``` + +--- + +These methods and techniques enable developers to interact with the DOM dynamically, providing a powerful way to enhance the user experience of web applications. + +# Section 16. What's Next Step? + +Great Job! Thank You for looking into JavaScript for Beginners. I hope you enjoyed and learned a lot out of it. I think Now you have better understandings of how JavaScript works and functions. To learn more about JavaScript visit [Mozilla JavaScript Reference Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript). + +- Your Next step could be looking into advanced topics of [HTML5](https://github.com/dinanathsj29/html5-semantic-tags), [CSS3] or [JavaScript]. - For detailed view on JavaScript look into [Advanced JavaScript Tutorial], [JavaScript ES6 Tutorial](https://github.com/dinanathsj29/ES6-ECMAScript6-ECMAScript2015-tutorial) or [TypeScript Tutorials](https://github.com/dinanathsj29/typescript-tutorial). -- You may move forward with any famous and popular JavaScript Frameworks or Libraries like jQuery.js, [Angular](https://github.com/dinanathsj29/angular7-step-by-step), React.js, NPM, Node.js, Vue.js etc. +- You may move forward with any famous and popular JavaScript Frameworks or Libraries like jQuery.js, [Angular](https://github.com/dinanathsj29/angular7-step-by-step), React.js, NPM, Node.js, Vue.js etc. Best of Luck! Happy Learning! - <!-- -Local and Session Storage +Local and Session Storage - In `Browser -> Inspect Element -> Console Panel` -> Type `Window`, check different properties and methods available -> localStorage diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html new file mode 100644 index 0000000..462a878 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html @@ -0,0 +1,68 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.03.01.js.dom.byid.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.03. JavaScript DOM Selectors - 14.03.01. Selecting Elements by ID (`getElementById()`)</h2> + + <ul class="normalList"> + <li>One can select an element based on its `unique ID` with the `getElementById()` method</li> + <li>`getElementById()` is the easiest and most common way to find/access an HTML element in the DOM tree</li> + <li>`getElementById()` method returns the element having the given id value</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.03.01.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js new file mode 100644 index 0000000..12b8430 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js @@ -0,0 +1,31 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); + +// get html of selected element +let mainHeadingHtml = mainHeadingElement.innerHTML; + +// get text of selected element +let mainHeadingText = mainHeadingElement.innerText; +console.log('mainHeadingHtml: ' + mainHeadingHtml); // text with complete html tags +console.log('mainHeadingText: ' + mainHeadingText); // only text + +// console.log('// ------------------------------'); + +// set text of selected element +mainHeadingElement.innerHTML = 'This text changed with DOM method...'; + +// console.log('// ------------------------------'); + +// set text of another element +let subHeadingElement = document.getElementById('subHeadingText'); +subHeadingElement.innerHTML = mainHeadingElement.innerHTML ; + +// console.log('// ------------------------------'); + +// set css style +mainHeadingElement.style.backgroundColor = 'pink'; + +// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html new file mode 100644 index 0000000..5b9ac64 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html @@ -0,0 +1,67 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.03.02.js.dom.byclass.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.03. JavaScript DOM Selectors - 14.03.02. Selecting Elements by Class Name (`getElementsByClassName()`)</h2> + + <ul class="normalList"> + <li>`getElementsByClassName()` method is used to select all the `elements having specific class names`</li> + <li>`getElementsByClassName()` method `returns an array of all elements` with given class names</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.03.02.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js new file mode 100644 index 0000000..731ad72 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js @@ -0,0 +1,26 @@ +// external js file +// Write all JavaScript code here + +// Selecting elements with class +let listItems = document.getElementsByClassName('list-item'); +console.log(listItems); + +// get text of 1st ie 0th element +let firstListItemText = listItems[0].innerHTML; +console.log('firstListItemText: ' + firstListItemText); + +// console.log('// ------------------------------'); + +// set color of last element +let lastListItem = (listItems.length - 1); +listItems[lastListItem].style.color = 'blue'; + +// console.log('// ------------------------------'); + +// highlighting all list items through loop +for(var listItem in listItems) { + listItems[listItem].style.marginBottom = '10px'; + listItems[listItem].style.background = '#bbbbbb'; +} + +// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html new file mode 100644 index 0000000..3a584cf --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html @@ -0,0 +1,67 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.03.03.js.dom.bytag.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.03. JavaScript DOM Selectors - 14.03.03. Selecting Elements by Tag Name (`getElementsByTagName()`)</h2> + + <ul class="normalList"> + <li>Developer can also `select HTML elements by tag name` using the `getElementsByTagName()` method</li> + <li>`getElementsByTagName()` method `returns an array of all elements` with given tag name</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.03.03.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js new file mode 100644 index 0000000..10d664a --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js @@ -0,0 +1,34 @@ +// external js file +// Write all JavaScript code here + +// Selecting all LI elements with tag name +let liElements = document.getElementsByTagName('li'); +console.log(liElements); + +// console.log('// ------------------------------'); + +// get total li tags/elements in page +let totalLiElements = liElements.length; +console.log(totalLiElements); + +// console.log('// ------------------------------'); + +// get text of 1st ie 0th li element +let firstLiText = liElements[0].innerHTML; +console.log('firstLiText: ' + firstLiText); + +// console.log('// ------------------------------'); + +// set text of last element +let lastLi = (liElements.length - 1); +liElements[lastLi].style.color = 'blue'; + +// console.log('// ------------------------------'); + +// highlighting all li elements through loop +for(var li in liElements) { + liElements[li].style.marginBottom = '10px'; + liElements[li].style.background = '#bbbbbb'; +} + +// console.log('// ------------------------------'); \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html new file mode 100644 index 0000000..b04aed2 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html @@ -0,0 +1,68 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.03.04.js.dom.queryselector.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.03. JavaScript DOM Selectors - 14.03.04. Selecting Elements with CSS Selectors (`querySelectorAll()`)</h2> + + <ul class="normalList"> + <li>`querySelectorAll()` method find all `HTML elements that match a specified CSS selector` (id, class names, types, attributes, values of attributes, etc)</li> + <li>CSS selectors provide a very `powerful and efficient way` of selecting HTML elements in a document</li> + <li>`querySelectorAll()` method `returns an array` or list of all the elements that matches the specified selectors</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.03.04.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js new file mode 100644 index 0000000..f3e392c --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js @@ -0,0 +1,15 @@ +// external js file +// Write all JavaScript code here + +// Selecting all ul -> li elements +let ulLiElement = document.querySelectorAll('ul li'); +console.log(ulLiElement); + +let ulListItemClass = document.querySelectorAll("ul li.list-item") +console.log(ulListItemClass); + +// set color of last li element +ulLiElement[ulLiElement.length - 1].style.color = 'red'; + +// set text of last li element +ulLiElement[ulLiElement.length - 1].innerHTML = 'Dynamic text change at run time'; diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html new file mode 100644 index 0000000..8fe10b6 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html @@ -0,0 +1,70 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.04.01.js.dom.apply.set.style.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.04. JavaScript DOM CSS Styling</h2> + Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. + + <h2>14.04.01. Applying/Setting Inline Styles on Elements</h2> + + <ul class="normalList"> + <li>In HTML inline styles are applied directly to the specific HTML element using the `style attribute`, eg. `<element style="color:red;">`</li> + <li>In JavaScript the `style property` is used to get or set the inline style of an element, eg. `elem.style.color = 'red';`</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.04.01.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js new file mode 100644 index 0000000..fd1806e --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js @@ -0,0 +1,13 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); + +// set css style +mainHeadingElement.style.padding = '5px'; +mainHeadingElement.style.backgroundColor = 'pink'; +mainHeadingElement.style.color = 'blue'; +mainHeadingElement.style.border = '5px solid #999999'; + +// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html new file mode 100644 index 0000000..155ea03 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html @@ -0,0 +1,77 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.04.02.js.dom.retreive.get.style.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + #mainHeadingText { + color:blue; + border:5px solid #999999; + } + + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.04. JavaScript DOM CSS Styling</h2> + Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. + + <h2>14.04.02. Retrieving/Getting CSS Styles details from Elements</h2> + + <ul class="normalList"> + <li>We can get the styles applied on the HTML elements using the `style property`</li> + <li>`style property` only returns the style rules set in the element's style attribute not those applied through internal/embedded style sheets, or external style sheets</li> + <li>To get the values of all CSS properties that are actually render an element we can use the `window.getComputedStyle()` method</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.04.02.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js new file mode 100644 index 0000000..25f7fbf --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js @@ -0,0 +1,22 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); + +// set css style +mainHeadingElement.style.padding = '5px'; +mainHeadingElement.style.backgroundColor = 'pink'; + +// console.log('// ------------------------------'); + +// get inline css styles +console.log('mainHeadingElement.style.padding:',mainHeadingElement.style.padding); +console.log('mainHeadingElement.style.backgroundColor:',mainHeadingElement.style.backgroundColor); + +// console.log('// ------------------------------'); + +// get computed style information/ any type of css styles internal/embedded style sheets +var cssStyles = window.getComputedStyle(mainHeadingElement); +console.log('internal style - color:',cssStyles.color); +console.log('internal style - border:',cssStyles.border); \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html new file mode 100644 index 0000000..5e801a6 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html @@ -0,0 +1,84 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.04.03.js.dom.css.class.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + .heading-text { + color:blue; + + } + + .border { + border:5px solid #999999; + } + + .bg-color { + background-color:pink; + } + + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.04. JavaScript DOM CSS Styling</h2> + Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. + + <h2>14.04.03. Applying/Adding CSS Classes to Elements</h2> + + <ul class="normalList"> + <li>We can also get or set CSS classes to the HTML elements using the `className property`</li> + <li>As `class` is a reserved word in JavaScript, it uses the `className` property to refer the value of the HTML class attribute</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.04.03.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js new file mode 100644 index 0000000..c2588fd --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js @@ -0,0 +1,11 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); + +// remove old classes and apply/set css class +mainHeadingElement.className = 'bg-color'; + +// apply/set css class +mainHeadingElement.className += ' border'; \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html new file mode 100644 index 0000000..0011ab1 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html @@ -0,0 +1,86 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.04.04.js.dom.css.classlist.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + .heading-text { + color:blue; + + } + + .border { + border:5px solid #999999; + } + + .bg-color { + background-color:pink; + } + + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.04. JavaScript DOM CSS Styling</h2> + Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. + + <h2>14.04.03. Applying/Adding CSS Classes to Elements</h2> + + <ul class="normalList"> + <li>We can also get or set CSS classes to the HTML elements using the `className property`</li> + <li>As `class` is a reserved word in JavaScript, it uses the `className` property to refer the value of the HTML class attribute</li> + <li>Using `classList property` is much easier and better to get, set or remove CSS classes from an element</li> + <li>`classList property` is supported in all major browsers except Internet Explorer prior to version 10</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.04.04.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js new file mode 100644 index 0000000..368302f --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js @@ -0,0 +1,26 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); + +// apply/set/add css class with classList +mainHeadingElement.classList.add('heading-text'); + +// apply/set/add css class with classList +mainHeadingElement.classList.add('border','bg-color'); + +// remove classes with classList +mainHeadingElement.classList.remove('border','bg-color'); + +// if class exists remove it, if not add it +mainHeadingElement.classList.toggle('heading-text'); + +// mainHeadingElement.classList.add('border'); + +// check if class exist and act accordingly +if(mainHeadingElement.classList.contains('border')) { + alert('border class present'); +} else { + alert('NO border class present'); +} \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html new file mode 100644 index 0000000..7a7e18e --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html @@ -0,0 +1,85 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.05.01.js.dom.attribute.apply.set.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + .btn { + padding: 0.5rem; + cursor: pointer; + color:blue; + background-color: rgb(176, 176, 250); + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <button class="click-button" id="clickButton">Click Me</button> + + Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> + <ul class="normalList"> + <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> + <li>An HTML attribute contains two fields: `name & value / key & value`</li> + <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> + </ul> + + <h2>14.05.01. Applying/Setting Attribute on Element</h2> + + <ul class="normalList"> + <li>The `setAttribute()` method is used to set an attribute on the specified element</li> + <li>If the attribute already present/exists on the element, the attribute value will be updated; else a new attribute is added with the specified name and value</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.05.01.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js new file mode 100644 index 0000000..498476d --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js @@ -0,0 +1,18 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); +let clickButtonElement = document.getElementById('clickButton'); +let linkTextElement = document.getElementById('linkText'); + +// set attribute class named 'btn' +mainHeadingElement.setAttribute('class', 'btn'); + +// set attribute disabled +clickButtonElement.setAttribute('disabled', ''); + +// set blank/empty attribute so that it will remove exisiting attribute value +linkTextElement.setAttribute('href',''); + +// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html new file mode 100644 index 0000000..c7d3fbc --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html @@ -0,0 +1,85 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.05.02.js.dom.attribute.retreive.get.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + .btn { + padding: 0.5rem; + cursor: pointer; + color:blue; + background-color: rgb(176, 176, 250); + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <button class="click-button" id="clickButton">Click Me</button> + + Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> + <ul class="normalList"> + <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> + <li>An HTML attribute contains two fields: `name & value / key & value`</li> + <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> + </ul> + + <h2>14.05.02. Retrieving/Getting Attribute Value</h2> + + <ul class="normalList"> + <li>The `getAttribute()` method is used to get the current value of a attribute on the element</li> + <li>If the specified attribute does not present/exists on the element, it will return `null`</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.05.02.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js new file mode 100644 index 0000000..71b01aa --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js @@ -0,0 +1,19 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); +let clickButtonElement = document.getElementById('clickButton'); +let linkTextElement = document.getElementById('linkText'); + +// getting the attributes values +let getAttrClass = mainHeadingElement.getAttribute('class'); +console.log('getAttrClass:', getAttrClass); + +let getAttrDisabled = clickButtonElement.getAttribute('disabled'); +console.log('getAttrDisabled:', getAttrDisabled); + +let getAttrHref = linkTextElement.getAttribute('href'); +console.log('getAttrHref:', getAttrHref); + +// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html new file mode 100644 index 0000000..cd61524 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html @@ -0,0 +1,84 @@ +<!DOCTYPE html> +<html lang="en"> + + <head> + + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <meta http-equiv="X-UA-Compatible" content="ie=edge"> + <title>14.05.03.js.dom.attribute.remove.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + + .btn { + padding: 0.5rem; + cursor: pointer; + color:blue; + background-color: rgb(176, 176, 250); + } + </style> + + </head> + + <body> + + <div class="container"> + + <div class="sub-container"> + + <h1 class="heading-text btn" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> + + <button class="click-button" id="clickButton" disabled>Click Me</button> + + Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> + + <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> + + <ul> + <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> + <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> + <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> + <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> + <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> + </ul> + + <h2>14.02. Node</h2> + As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> + There are different types of nodes like: `Elements, Attribute & Text Node`. + +<pre> + <ul id="list" --> Element & Attribute NODE + <li>first item </li> --> text NODE + </ul + + * Elements NODES not contains text +</pre> + + <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> + <ul class="normalList"> + <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> + <li>An HTML attribute contains two fields: `name & value / key & value`</li> + <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> + </ul> + + <h2>14.05.03. Removing Attributes from Elements</h2> + + <ul class="normalList"> + <li>The `removeAttribute()` method is used to remove an attribute from the specified element</li> + </ul> + + </div> + + </div> + + <!-- include external JavaScript - body section --> + <script src="./14.05.03.script.js"></script> + + </body> + +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js new file mode 100644 index 0000000..8cb3b1d --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js @@ -0,0 +1,22 @@ +// external js file +// Write all JavaScript code here + +// Selecting element with id +let mainHeadingElement = document.getElementById('mainHeadingText'); +let clickButtonElement = document.getElementById('clickButton'); +let linkTextElement = document.getElementById('linkText'); + +// removing the attributes +mainHeadingElement.removeAttribute('class'); + +// verify/confirm class removed or not +console.log('mainHeadingElement.getAttribute:', mainHeadingElement.getAttribute('class')); +console.log('mainHeadingElement.classList.contains:', mainHeadingElement.classList.contains('class')); + +// console.log('// ------------------------------'); + +clickButtonElement.removeAttribute('disabled'); + +linkTextElement.removeAttribute('href'); + +// console.log('// ------------------------------'); From eaa18d98303d9552aba23f60725bb7c7f1e04ea0 Mon Sep 17 00:00:00 2001 From: Mejbaul Mubin <mejbaulmubin@my.uopeople.edu> Date: Fri, 3 Jan 2025 16:03:05 +0600 Subject: [PATCH 2/3] Dynamic DOM Manipulation is complite --- README.md | 60 ++++++++------ .../01/15.02.01.js.dom.ClassManipulation.html | 12 +++ .../15. DOM (Advanced)/01/15.02.01.script.js | 2 + .../01/15.03.01.js.dom.FormValidation.html | 20 +++++ ....js.dom.DynamicInputFieldManipulation.html | 16 ++++ .../{ => 14. DOM}/14.03.01.js.dom.byid.html | 0 .../{ => 14. DOM}/14.03.01.script.js | 0 .../14.03.02.js.dom.byclass.html | 0 .../{ => 14. DOM}/14.03.02.script.js | 0 .../{ => 14. DOM}/14.03.03.js.dom.bytag.html | 0 .../{ => 14. DOM}/14.03.03.script.js | 0 .../14.03.04.js.dom.queryselector.html | 0 .../{ => 14. DOM}/14.03.04.script.js | 0 .../14.04.01.js.dom.apply.set.style.html | 0 .../{ => 14. DOM}/14.04.01.script.js | 0 .../14.04.02.js.dom.retreive.get.style.html | 0 .../{ => 14. DOM}/14.04.02.script.js | 0 .../14.04.03.js.dom.css.class.html | 0 .../{ => 14. DOM}/14.04.03.script.js | 0 .../14.04.04.js.dom.css.classlist.html | 0 .../{ => 14. DOM}/14.04.04.script.js | 0 .../14.05.01.js.dom.attribute.apply.set.html | 0 .../{ => 14. DOM}/14.05.01.script.js | 0 ...4.05.02.js.dom.attribute.retreive.get.html | 0 .../{ => 14. DOM}/14.05.02.script.js | 0 .../14.05.03.js.dom.attribute.remove.html | 0 .../{ => 14. DOM}/14.05.03.script.js | 0 .../15.01.01.js.dom.AppendingElements.html | 81 ++++++++++++++++++ .../15. DOM (Advanced)/15.01.01.script.js | 21 +++++ .../15.01.02.js.dom.RemovingElements.html | 83 +++++++++++++++++++ .../15. DOM (Advanced)/15.01.02.script.js | 8 ++ .../15.01.03.js.dom.ReplacingElements.html | 82 ++++++++++++++++++ .../15. DOM (Advanced)/15.01.03.script.js | 15 ++++ 33 files changed, 375 insertions(+), 25 deletions(-) create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.01.js.dom.byid.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.01.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.02.js.dom.byclass.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.02.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.03.js.dom.bytag.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.03.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.04.js.dom.queryselector.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.03.04.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.01.js.dom.apply.set.style.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.01.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.02.js.dom.retreive.get.style.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.02.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.03.js.dom.css.class.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.03.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.04.js.dom.css.classlist.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.04.04.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.01.js.dom.attribute.apply.set.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.01.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.02.js.dom.attribute.retreive.get.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.02.script.js (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.03.js.dom.attribute.remove.html (100%) rename _examples_javascript_beginners/15. DOM (Advanced)/{ => 14. DOM}/14.05.03.script.js (100%) create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.01.js.dom.AppendingElements.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.02.js.dom.RemovingElements.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.02.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.03.js.dom.ReplacingElements.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.01.03.script.js diff --git a/README.md b/README.md index 16dad64..188eea7 100644 --- a/README.md +++ b/README.md @@ -4344,20 +4344,27 @@ You can create new HTML elements dynamically using the `document.createElement() > **Syntax & Example:** ```javascript -// Create a new element -let newParagraph = document.createElement("p"); +// Select the <ul> element +let ulElement = document.querySelector("ul"); -// Add text content to the new element -newParagraph.innerText = "This is a dynamically created paragraph."; +// Create a new <li> element +let newParagraph = document.createElement("li"); -// Append the new element to an existing parent element -let parentElement = document.getElementById("content"); -parentElement.appendChild(newParagraph); +// Add text content to the new <li> element +newParagraph.innerText = + "The DOM tree serves as a foundational structure that JavaScript can traverse and modify, enabling developers to construct intricate and dynamic web pages. (This is a dynamically created li element)."; -// Alternative: Use append() for modern browsers +// Append the new <li> to the <ul> +ulElement.appendChild(newParagraph); + +// Create a new <span> element let newSpan = document.createElement("span"); -newSpan.innerText = " Appended using append()."; -parentElement.append(newSpan); + +// Add text content to the <span> element +newSpan.innerText = " (Appended using a span element)"; + +// Append the <span> to the newly created <li> +newParagraph.appendChild(newSpan); ``` ### 15.01.02. Removing Elements @@ -4368,15 +4375,13 @@ Elements can be removed using `removeChild()` or the more modern `remove()` meth ```javascript // Select the element to be removed -let elementToRemove = document.getElementById("oldItem"); +let ulElement = document.querySelector("ul"); -// Remove the element using removeChild() -let parentElement = elementToRemove.parentElement; -parentElement.removeChild(elementToRemove); +// Select the last child element of the <ul> and remove it +ulElement.removeChild(ulElement.lastElementChild); -// Alternative: Use remove() for modern browsers -let anotherElementToRemove = document.getElementById("unusedItem"); -anotherElementToRemove.remove(); +// Select the first child element of the <ul> and remove it using the newer remove() method +ulElement.firstElementChild.remove(); ``` ### 15.01.03. Replacing Elements @@ -4386,16 +4391,21 @@ Replace an existing DOM element with another using the `replaceChild()` method. > **Syntax & Example:** ```javascript -// Create a new element -let replacementElement = document.createElement("h2"); -replacementElement.innerText = "This is the replacement element."; +// Select the <ul> element +let ulElement = document.querySelector("ul"); + +// Create a new <li> element +let newListItem = document.createElement("li"); + +// Add text to the new <li> element +newListItem.textContent = + "The DOM tree serves as a foundational structure that JavaScript can traverse and modify, enabling developers to construct intricate and dynamic web pages.(This is the new replaced item.)"; -// Select the element to replace -let oldElement = document.getElementById("replaceMe"); +// Select the child element to be replaced +let itemToReplace = ulElement.children[3]; // Replacing the 4th item (index starts at 0) -// Replace the old element -let parentElement = oldElement.parentElement; -parentElement.replaceChild(replacementElement, oldElement); +// Replace the old item with the new one +ulElement.replaceChild(newListItem, itemToReplace); ``` --- diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html new file mode 100644 index 0000000..3a4e7c8 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html @@ -0,0 +1,12 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Class Manipulation</title> + </head> + <body> + <div id="box" style="border: 1px solid; padding: 10px">This is a box</div> + <script src="./15.02.01.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js new file mode 100644 index 0000000..6e430b8 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js @@ -0,0 +1,2 @@ +let element = document.getElementById("box"); +element.classList.add("highlight", "rounded"); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html new file mode 100644 index 0000000..b7089c4 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html @@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Form Validation</title> + </head> + <body> + <form id="registrationForm"> + <label for="username">Username:</label> + <input type="text" id="username" name="username" required /> + <br /> + <label for="email">Email:</label> + <input type="email" id="email" name="email" required /> + <br /> + <button type="submit">Register</button> + </form> + <script src="./15.03.01.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html new file mode 100644 index 0000000..9d1056e --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Dynamic Input Fields</title> + </head> + <body> + <div id="inputContainer"> + <p>Input fields:</p> + </div> + <button id="addInput">Add Input</button> + <button id="removeInput">Remove Last Input</button> + <script src="./15.03.02.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.01.js.dom.byid.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.01.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.02.js.dom.byclass.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.02.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.03.js.dom.bytag.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.03.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.04.js.dom.queryselector.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.03.04.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.01.js.dom.apply.set.style.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.01.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.02.js.dom.retreive.get.style.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.02.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.03.js.dom.css.class.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.03.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.04.js.dom.css.classlist.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.04.04.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.01.js.dom.attribute.apply.set.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.01.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.02.js.dom.attribute.retreive.get.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.02.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.03.js.dom.attribute.remove.html rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js similarity index 100% rename from _examples_javascript_beginners/15. DOM (Advanced)/14.05.03.script.js rename to _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.js.dom.AppendingElements.html b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.js.dom.AppendingElements.html new file mode 100644 index 0000000..1d6ef29 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.js.dom.AppendingElements.html @@ -0,0 +1,81 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>15.DOM.Advanced.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + </head> + + <body> + <div class="container"> + <div class="sub-container"> + <h1 class="heading-text" id="mainHeadingText"> + <font>15. DOM (Advanced)</font> + </h1> + + <h2 class="sub-heading-text" id="subHeadingText"> + 15.01. Dynamic DOM Manipulation + </h2> + <ul> + <li class="list-item"> + Dynamic DOM manipulation involves creating, modifying, and deleting + elements and their attributes in real-time using JavaScript. + </li> + <li class="list-item"> + Common methods include `createElement()`, `appendChild()`, + `removeChild()`, and `replaceChild()`. + </li> + <li class="list-item"> + Developers can add interactivity and dynamic content to web pages by + manipulating the DOM tree. + </li> + </ul> + + <h2>15.02. Class Manipulation</h2> + <ul> + <li> + JavaScript provides methods to manipulate CSS classes for elements + dynamically. + </li> + <li> + Methods like `classList.add()`, `classList.remove()`, + `classList.toggle()`, and `classList.contains()` are commonly used + for class manipulation. + </li> + <li> + Class manipulation helps in controlling element styles and behavior + programmatically. + </li> + </ul> + + <h2>15.03. Handling Forms and Input Fields</h2> + <ul> + <li> + DOM provides methods to interact with forms and input fields, making + it easy to capture, validate, and process user inputs. + </li> + <li> + Commonly used methods include `getElementById()`, `querySelector()`, + and event listeners like `onchange`, `onsubmit`, and `onclick`. + </li> + <li> + Dynamic form handling can be achieved by modifying the `value`, + `checked`, and `selected` properties of input fields. + </li> + </ul> + </div> + </div> + + <!-- include external JavaScript - body section --> + <script src="./15.01.01.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.script.js new file mode 100644 index 0000000..c093ee5 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.01.script.js @@ -0,0 +1,21 @@ +// Select the <ul> element +let ulElement = document.querySelector("ul"); + +// Create a new <li> element +let newParagraph = document.createElement("li"); + +// Add text content to the new <li> element +newParagraph.innerText = + "The DOM tree serves as a foundational structure that JavaScript can traverse and modify, enabling developers to construct intricate and dynamic web pages. (This is a dynamically created li element)."; + +// Append the new <li> to the <ul> +ulElement.appendChild(newParagraph); + +// Create a new <span> element +let newSpan = document.createElement("span"); + +// Add text content to the <span> element +newSpan.innerText = " (Appended using a span element)"; + +// Append the <span> to the newly created <li> +newParagraph.appendChild(newSpan); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.js.dom.RemovingElements.html b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.js.dom.RemovingElements.html new file mode 100644 index 0000000..1a618dc --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.js.dom.RemovingElements.html @@ -0,0 +1,83 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>15.DOM.Advanced.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + </head> + + <body> + <div class="container"> + <div class="sub-container"> + <h1 class="heading-text" id="mainHeadingText"> + <font>15. DOM (Advanced)</font> + </h1> + + <h2 class="sub-heading-text" id="subHeadingText"> + 15.01. Dynamic DOM Manipulation + </h2> + <ul> + <li class="list-item">First Item.</li> + <li class="list-item"> + Dynamic DOM manipulation involves creating, modifying, and deleting + elements and their attributes in real-time using JavaScript. + </li> + <li class="list-item"> + Common methods include `createElement()`, `appendChild()`, + `removeChild()`, and `replaceChild()`. + </li> + <li class="list-item"> + Developers can add interactivity and dynamic content to web pages by + manipulating the DOM tree. + </li> + <li class="list-item">Last Item.</li> + </ul> + + <h2>15.02. Class Manipulation</h2> + <ul> + <li> + JavaScript provides methods to manipulate CSS classes for elements + dynamically. + </li> + <li> + Methods like `classList.add()`, `classList.remove()`, + `classList.toggle()`, and `classList.contains()` are commonly used + for class manipulation. + </li> + <li> + Class manipulation helps in controlling element styles and behavior + programmatically. + </li> + </ul> + + <h2>15.03. Handling Forms and Input Fields</h2> + <ul> + <li> + DOM provides methods to interact with forms and input fields, making + it easy to capture, validate, and process user inputs. + </li> + <li> + Commonly used methods include `getElementById()`, `querySelector()`, + and event listeners like `onchange`, `onsubmit`, and `onclick`. + </li> + <li> + Dynamic form handling can be achieved by modifying the `value`, + `checked`, and `selected` properties of input fields. + </li> + </ul> + </div> + </div> + + <!-- include external JavaScript - body section --> + <script src="./15.01.02.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.script.js new file mode 100644 index 0000000..8d690e1 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.02.script.js @@ -0,0 +1,8 @@ +// Select the element to be removed +let ulElement = document.querySelector("ul"); + +// Select the last child element of the <ul> and remove it +ulElement.removeChild(ulElement.lastElementChild); + +// Select the first child element of the <ul> and remove it using the newer remove() method +ulElement.firstElementChild.remove(); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.js.dom.ReplacingElements.html b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.js.dom.ReplacingElements.html new file mode 100644 index 0000000..52a0e7b --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.js.dom.ReplacingElements.html @@ -0,0 +1,82 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>15.DOM.Advanced.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + </head> + + <body> + <div class="container"> + <div class="sub-container"> + <h1 class="heading-text" id="mainHeadingText"> + <font>15. DOM (Advanced)</font> + </h1> + + <h2 class="sub-heading-text" id="subHeadingText"> + 15.01. Dynamic DOM Manipulation + </h2> + <ul> + <li class="list-item"> + Dynamic DOM manipulation involves creating, modifying, and deleting + elements and their attributes in real-time using JavaScript. + </li> + <li class="list-item"> + Common methods include `createElement()`, `appendChild()`, + `removeChild()`, and `replaceChild()`. + </li> + <li class="list-item"> + Developers can add interactivity and dynamic content to web pages by + manipulating the DOM tree. + </li> + <li class="list-item">This is the paragraph to be replaced.</li> + </ul> + + <h2>15.02. Class Manipulation</h2> + <ul> + <li> + JavaScript provides methods to manipulate CSS classes for elements + dynamically. + </li> + <li> + Methods like `classList.add()`, `classList.remove()`, + `classList.toggle()`, and `classList.contains()` are commonly used + for class manipulation. + </li> + <li> + Class manipulation helps in controlling element styles and behavior + programmatically. + </li> + </ul> + + <h2>15.03. Handling Forms and Input Fields</h2> + <ul> + <li> + DOM provides methods to interact with forms and input fields, making + it easy to capture, validate, and process user inputs. + </li> + <li> + Commonly used methods include `getElementById()`, `querySelector()`, + and event listeners like `onchange`, `onsubmit`, and `onclick`. + </li> + <li> + Dynamic form handling can be achieved by modifying the `value`, + `checked`, and `selected` properties of input fields. + </li> + </ul> + </div> + </div> + + <!-- include external JavaScript - body section --> + <script src="./15.01.03.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.script.js new file mode 100644 index 0000000..de68dcd --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.01.03.script.js @@ -0,0 +1,15 @@ +// Select the <ul> element +let ulElement = document.querySelector("ul"); + +// Create a new <li> element +let newListItem = document.createElement("li"); + +// Add text to the new <li> element +newListItem.textContent = + "The DOM tree serves as a foundational structure that JavaScript can traverse and modify, enabling developers to construct intricate and dynamic web pages.(This is the new replaced item.)"; + +// Select the child element to be replaced +let itemToReplace = ulElement.children[3]; // Replacing the 4th item (index starts at 0) + +// Replace the old item with the new one +ulElement.replaceChild(newListItem, itemToReplace); From 3e80f69095a5218910f295e5be4d63c62f27f460 Mon Sep 17 00:00:00 2001 From: Mejbaul Mubin <mejbaulmubin@my.uopeople.edu> Date: Fri, 3 Jan 2025 17:13:40 +0600 Subject: [PATCH 3/3] Remove class is added --- README.md | 22 ++++- .../01/15.02.01.js.dom.ClassManipulation.html | 12 --- .../15. DOM (Advanced)/01/15.02.01.script.js | 2 - .../01/15.03.01.js.dom.FormValidation.html | 20 ----- ....js.dom.DynamicInputFieldManipulation.html | 16 ---- .../14. DOM/14.03.01.js.dom.byid.html | 68 --------------- .../14. DOM/14.03.01.script.js | 31 ------- .../14. DOM/14.03.02.js.dom.byclass.html | 67 --------------- .../14. DOM/14.03.02.script.js | 26 ------ .../14. DOM/14.03.03.js.dom.bytag.html | 67 --------------- .../14. DOM/14.03.03.script.js | 34 -------- .../14.03.04.js.dom.queryselector.html | 68 --------------- .../14. DOM/14.03.04.script.js | 15 ---- .../14.04.01.js.dom.apply.set.style.html | 70 --------------- .../14. DOM/14.04.01.script.js | 13 --- .../14.04.02.js.dom.retreive.get.style.html | 77 ----------------- .../14. DOM/14.04.02.script.js | 22 ----- .../14. DOM/14.04.03.js.dom.css.class.html | 84 ------------------ .../14. DOM/14.04.03.script.js | 11 --- .../14.04.04.js.dom.css.classlist.html | 86 ------------------- .../14. DOM/14.04.04.script.js | 26 ------ .../14.05.01.js.dom.attribute.apply.set.html | 85 ------------------ .../14. DOM/14.05.01.script.js | 18 ---- ...4.05.02.js.dom.attribute.retreive.get.html | 85 ------------------ .../14. DOM/14.05.02.script.js | 19 ---- .../14.05.03.js.dom.attribute.remove.html | 84 ------------------ .../14. DOM/14.05.03.script.js | 22 ----- .../15.02.01.js.dom.AddingClasses.html | 81 +++++++++++++++++ .../15. DOM (Advanced)/15.02.01.script.js | 13 +++ .../15.02.02.js.dom.RemovingClasses.html | 81 +++++++++++++++++ .../15. DOM (Advanced)/15.02.02.script.js | 5 ++ 31 files changed, 198 insertions(+), 1132 deletions(-) delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html delete mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.02.01.js.dom.AddingClasses.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.02.01.script.js create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.02.02.js.dom.RemovingClasses.html create mode 100644 _examples_javascript_beginners/15. DOM (Advanced)/15.02.02.script.js diff --git a/README.md b/README.md index 188eea7..55e946c 100644 --- a/README.md +++ b/README.md @@ -4421,8 +4421,19 @@ Add one or more classes to an element. > **Syntax & Example:** ```javascript -let element = document.getElementById("box"); -element.classList.add("highlight", "rounded"); +// Select the second <ul> +let secondUl = document.querySelectorAll("ul")[1]; // 0-based index, so 1 means the second <ul> + +// Add a class to the first <ul> +secondUl.classList.add("second-ul-class"); + +// Select all <li> children of the second <ul> +let liElements = secondUl.querySelectorAll("li"); + +// Add a class to each <li> of the second <ul> +liElements.forEach((li, index) => { + li.classList.add(`second-ul-li-${index + 1}`); +}); ``` ### 15.02.02. Removing Classes: `classList.remove()` @@ -4432,8 +4443,11 @@ Remove one or more classes from an element. > **Syntax & Example:** ```javascript -let element = document.getElementById("box"); -element.classList.remove("highlight", "rounded"); +// Select the second <ul> +let secondUl = document.querySelectorAll("ul")[1]; + +// remove class "second-ul-class" <ul> +secondUl.classList.remove("second-ul-class"); ``` ### 15.02.02. Toggling Classes: `classList.toggle()` diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html deleted file mode 100644 index 3a4e7c8..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.js.dom.ClassManipulation.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="UTF-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>Class Manipulation</title> - </head> - <body> - <div id="box" style="border: 1px solid; padding: 10px">This is a box</div> - <script src="./15.02.01.script.js"></script> - </body> -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js deleted file mode 100644 index 6e430b8..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.02.01.script.js +++ /dev/null @@ -1,2 +0,0 @@ -let element = document.getElementById("box"); -element.classList.add("highlight", "rounded"); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html deleted file mode 100644 index b7089c4..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.01.js.dom.FormValidation.html +++ /dev/null @@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="UTF-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>Form Validation</title> - </head> - <body> - <form id="registrationForm"> - <label for="username">Username:</label> - <input type="text" id="username" name="username" required /> - <br /> - <label for="email">Email:</label> - <input type="email" id="email" name="email" required /> - <br /> - <button type="submit">Register</button> - </form> - <script src="./15.03.01.script.js"></script> - </body> -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html b/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html deleted file mode 100644 index 9d1056e..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/01/15.03.02.js.dom.DynamicInputFieldManipulation.html +++ /dev/null @@ -1,16 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="UTF-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1.0" /> - <title>Dynamic Input Fields</title> - </head> - <body> - <div id="inputContainer"> - <p>Input fields:</p> - </div> - <button id="addInput">Add Input</button> - <button id="removeInput">Remove Last Input</button> - <script src="./15.03.02.script.js"></script> - </body> -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html deleted file mode 100644 index 462a878..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.js.dom.byid.html +++ /dev/null @@ -1,68 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.03.01.js.dom.byid.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.03. JavaScript DOM Selectors - 14.03.01. Selecting Elements by ID (`getElementById()`)</h2> - - <ul class="normalList"> - <li>One can select an element based on its `unique ID` with the `getElementById()` method</li> - <li>`getElementById()` is the easiest and most common way to find/access an HTML element in the DOM tree</li> - <li>`getElementById()` method returns the element having the given id value</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.03.01.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js deleted file mode 100644 index 12b8430..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.01.script.js +++ /dev/null @@ -1,31 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); - -// get html of selected element -let mainHeadingHtml = mainHeadingElement.innerHTML; - -// get text of selected element -let mainHeadingText = mainHeadingElement.innerText; -console.log('mainHeadingHtml: ' + mainHeadingHtml); // text with complete html tags -console.log('mainHeadingText: ' + mainHeadingText); // only text - -// console.log('// ------------------------------'); - -// set text of selected element -mainHeadingElement.innerHTML = 'This text changed with DOM method...'; - -// console.log('// ------------------------------'); - -// set text of another element -let subHeadingElement = document.getElementById('subHeadingText'); -subHeadingElement.innerHTML = mainHeadingElement.innerHTML ; - -// console.log('// ------------------------------'); - -// set css style -mainHeadingElement.style.backgroundColor = 'pink'; - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html deleted file mode 100644 index 5b9ac64..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.js.dom.byclass.html +++ /dev/null @@ -1,67 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.03.02.js.dom.byclass.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.03. JavaScript DOM Selectors - 14.03.02. Selecting Elements by Class Name (`getElementsByClassName()`)</h2> - - <ul class="normalList"> - <li>`getElementsByClassName()` method is used to select all the `elements having specific class names`</li> - <li>`getElementsByClassName()` method `returns an array of all elements` with given class names</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.03.02.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js deleted file mode 100644 index 731ad72..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.02.script.js +++ /dev/null @@ -1,26 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting elements with class -let listItems = document.getElementsByClassName('list-item'); -console.log(listItems); - -// get text of 1st ie 0th element -let firstListItemText = listItems[0].innerHTML; -console.log('firstListItemText: ' + firstListItemText); - -// console.log('// ------------------------------'); - -// set color of last element -let lastListItem = (listItems.length - 1); -listItems[lastListItem].style.color = 'blue'; - -// console.log('// ------------------------------'); - -// highlighting all list items through loop -for(var listItem in listItems) { - listItems[listItem].style.marginBottom = '10px'; - listItems[listItem].style.background = '#bbbbbb'; -} - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html deleted file mode 100644 index 3a584cf..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.js.dom.bytag.html +++ /dev/null @@ -1,67 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.03.03.js.dom.bytag.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.03. JavaScript DOM Selectors - 14.03.03. Selecting Elements by Tag Name (`getElementsByTagName()`)</h2> - - <ul class="normalList"> - <li>Developer can also `select HTML elements by tag name` using the `getElementsByTagName()` method</li> - <li>`getElementsByTagName()` method `returns an array of all elements` with given tag name</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.03.03.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js deleted file mode 100644 index 10d664a..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.03.script.js +++ /dev/null @@ -1,34 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting all LI elements with tag name -let liElements = document.getElementsByTagName('li'); -console.log(liElements); - -// console.log('// ------------------------------'); - -// get total li tags/elements in page -let totalLiElements = liElements.length; -console.log(totalLiElements); - -// console.log('// ------------------------------'); - -// get text of 1st ie 0th li element -let firstLiText = liElements[0].innerHTML; -console.log('firstLiText: ' + firstLiText); - -// console.log('// ------------------------------'); - -// set text of last element -let lastLi = (liElements.length - 1); -liElements[lastLi].style.color = 'blue'; - -// console.log('// ------------------------------'); - -// highlighting all li elements through loop -for(var li in liElements) { - liElements[li].style.marginBottom = '10px'; - liElements[li].style.background = '#bbbbbb'; -} - -// console.log('// ------------------------------'); \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html deleted file mode 100644 index b04aed2..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.js.dom.queryselector.html +++ /dev/null @@ -1,68 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.03.04.js.dom.queryselector.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.03. JavaScript DOM Selectors - 14.03.04. Selecting Elements with CSS Selectors (`querySelectorAll()`)</h2> - - <ul class="normalList"> - <li>`querySelectorAll()` method find all `HTML elements that match a specified CSS selector` (id, class names, types, attributes, values of attributes, etc)</li> - <li>CSS selectors provide a very `powerful and efficient way` of selecting HTML elements in a document</li> - <li>`querySelectorAll()` method `returns an array` or list of all the elements that matches the specified selectors</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.03.04.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js deleted file mode 100644 index f3e392c..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.03.04.script.js +++ /dev/null @@ -1,15 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting all ul -> li elements -let ulLiElement = document.querySelectorAll('ul li'); -console.log(ulLiElement); - -let ulListItemClass = document.querySelectorAll("ul li.list-item") -console.log(ulListItemClass); - -// set color of last li element -ulLiElement[ulLiElement.length - 1].style.color = 'red'; - -// set text of last li element -ulLiElement[ulLiElement.length - 1].innerHTML = 'Dynamic text change at run time'; diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html deleted file mode 100644 index 8fe10b6..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.js.dom.apply.set.style.html +++ /dev/null @@ -1,70 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.04.01.js.dom.apply.set.style.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.04. JavaScript DOM CSS Styling</h2> - Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. - - <h2>14.04.01. Applying/Setting Inline Styles on Elements</h2> - - <ul class="normalList"> - <li>In HTML inline styles are applied directly to the specific HTML element using the `style attribute`, eg. `<element style="color:red;">`</li> - <li>In JavaScript the `style property` is used to get or set the inline style of an element, eg. `elem.style.color = 'red';`</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.04.01.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js deleted file mode 100644 index fd1806e..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.01.script.js +++ /dev/null @@ -1,13 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); - -// set css style -mainHeadingElement.style.padding = '5px'; -mainHeadingElement.style.backgroundColor = 'pink'; -mainHeadingElement.style.color = 'blue'; -mainHeadingElement.style.border = '5px solid #999999'; - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html deleted file mode 100644 index 155ea03..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.js.dom.retreive.get.style.html +++ /dev/null @@ -1,77 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.04.02.js.dom.retreive.get.style.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - #mainHeadingText { - color:blue; - border:5px solid #999999; - } - - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.04. JavaScript DOM CSS Styling</h2> - Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. - - <h2>14.04.02. Retrieving/Getting CSS Styles details from Elements</h2> - - <ul class="normalList"> - <li>We can get the styles applied on the HTML elements using the `style property`</li> - <li>`style property` only returns the style rules set in the element's style attribute not those applied through internal/embedded style sheets, or external style sheets</li> - <li>To get the values of all CSS properties that are actually render an element we can use the `window.getComputedStyle()` method</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.04.02.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js deleted file mode 100644 index 25f7fbf..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.02.script.js +++ /dev/null @@ -1,22 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); - -// set css style -mainHeadingElement.style.padding = '5px'; -mainHeadingElement.style.backgroundColor = 'pink'; - -// console.log('// ------------------------------'); - -// get inline css styles -console.log('mainHeadingElement.style.padding:',mainHeadingElement.style.padding); -console.log('mainHeadingElement.style.backgroundColor:',mainHeadingElement.style.backgroundColor); - -// console.log('// ------------------------------'); - -// get computed style information/ any type of css styles internal/embedded style sheets -var cssStyles = window.getComputedStyle(mainHeadingElement); -console.log('internal style - color:',cssStyles.color); -console.log('internal style - border:',cssStyles.border); \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html deleted file mode 100644 index 5e801a6..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.js.dom.css.class.html +++ /dev/null @@ -1,84 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.04.03.js.dom.css.class.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - .heading-text { - color:blue; - - } - - .border { - border:5px solid #999999; - } - - .bg-color { - background-color:pink; - } - - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.04. JavaScript DOM CSS Styling</h2> - Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. - - <h2>14.04.03. Applying/Adding CSS Classes to Elements</h2> - - <ul class="normalList"> - <li>We can also get or set CSS classes to the HTML elements using the `className property`</li> - <li>As `class` is a reserved word in JavaScript, it uses the `className` property to refer the value of the HTML class attribute</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.04.03.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js deleted file mode 100644 index c2588fd..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.03.script.js +++ /dev/null @@ -1,11 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); - -// remove old classes and apply/set css class -mainHeadingElement.className = 'bg-color'; - -// apply/set css class -mainHeadingElement.className += ' border'; \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html deleted file mode 100644 index 0011ab1..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.js.dom.css.classlist.html +++ /dev/null @@ -1,86 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.04.04.js.dom.css.classlist.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - .heading-text { - color:blue; - - } - - .border { - border:5px solid #999999; - } - - .bg-color { - background-color:pink; - } - - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.04. JavaScript DOM CSS Styling</h2> - Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time . We can apply/set almost all the css styles for the elements like, fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on. - - <h2>14.04.03. Applying/Adding CSS Classes to Elements</h2> - - <ul class="normalList"> - <li>We can also get or set CSS classes to the HTML elements using the `className property`</li> - <li>As `class` is a reserved word in JavaScript, it uses the `className` property to refer the value of the HTML class attribute</li> - <li>Using `classList property` is much easier and better to get, set or remove CSS classes from an element</li> - <li>`classList property` is supported in all major browsers except Internet Explorer prior to version 10</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.04.04.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js deleted file mode 100644 index 368302f..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.04.04.script.js +++ /dev/null @@ -1,26 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); - -// apply/set/add css class with classList -mainHeadingElement.classList.add('heading-text'); - -// apply/set/add css class with classList -mainHeadingElement.classList.add('border','bg-color'); - -// remove classes with classList -mainHeadingElement.classList.remove('border','bg-color'); - -// if class exists remove it, if not add it -mainHeadingElement.classList.toggle('heading-text'); - -// mainHeadingElement.classList.add('border'); - -// check if class exist and act accordingly -if(mainHeadingElement.classList.contains('border')) { - alert('border class present'); -} else { - alert('NO border class present'); -} \ No newline at end of file diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html deleted file mode 100644 index 7a7e18e..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.js.dom.attribute.apply.set.html +++ /dev/null @@ -1,85 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.05.01.js.dom.attribute.apply.set.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - .btn { - padding: 0.5rem; - cursor: pointer; - color:blue; - background-color: rgb(176, 176, 250); - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <button class="click-button" id="clickButton">Click Me</button> - - Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> - <ul class="normalList"> - <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> - <li>An HTML attribute contains two fields: `name & value / key & value`</li> - <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> - </ul> - - <h2>14.05.01. Applying/Setting Attribute on Element</h2> - - <ul class="normalList"> - <li>The `setAttribute()` method is used to set an attribute on the specified element</li> - <li>If the attribute already present/exists on the element, the attribute value will be updated; else a new attribute is added with the specified name and value</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.05.01.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js deleted file mode 100644 index 498476d..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.01.script.js +++ /dev/null @@ -1,18 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); - -// set attribute class named 'btn' -mainHeadingElement.setAttribute('class', 'btn'); - -// set attribute disabled -clickButtonElement.setAttribute('disabled', ''); - -// set blank/empty attribute so that it will remove exisiting attribute value -linkTextElement.setAttribute('href',''); - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html deleted file mode 100644 index c7d3fbc..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.js.dom.attribute.retreive.get.html +++ /dev/null @@ -1,85 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.05.02.js.dom.attribute.retreive.get.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - .btn { - padding: 0.5rem; - cursor: pointer; - color:blue; - background-color: rgb(176, 176, 250); - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <button class="click-button" id="clickButton">Click Me</button> - - Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> - <ul class="normalList"> - <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> - <li>An HTML attribute contains two fields: `name & value / key & value`</li> - <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> - </ul> - - <h2>14.05.02. Retrieving/Getting Attribute Value</h2> - - <ul class="normalList"> - <li>The `getAttribute()` method is used to get the current value of a attribute on the element</li> - <li>If the specified attribute does not present/exists on the element, it will return `null`</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.05.02.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js deleted file mode 100644 index 71b01aa..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.02.script.js +++ /dev/null @@ -1,19 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); - -// getting the attributes values -let getAttrClass = mainHeadingElement.getAttribute('class'); -console.log('getAttrClass:', getAttrClass); - -let getAttrDisabled = clickButtonElement.getAttribute('disabled'); -console.log('getAttrDisabled:', getAttrDisabled); - -let getAttrHref = linkTextElement.getAttribute('href'); -console.log('getAttrHref:', getAttrHref); - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html deleted file mode 100644 index cd61524..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.js.dom.attribute.remove.html +++ /dev/null @@ -1,84 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - - <head> - - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <meta http-equiv="X-UA-Compatible" content="ie=edge"> - <title>14.05.03.js.dom.attribute.remove.html</title> - - <!-- internal style --> - <style> - /* css selector: { property:value; } */ - body { - font-family: arial; - } - - .btn { - padding: 0.5rem; - cursor: pointer; - color:blue; - background-color: rgb(176, 176, 250); - } - </style> - - </head> - - <body> - - <div class="container"> - - <div class="sub-container"> - - <h1 class="heading-text btn" id="mainHeadingText"><font>14. DOM (Document Object Model)</font></h1> - - <button class="click-button" id="clickButton" disabled>Click Me</button> - - Visit <a class="link-text" id="linkText" href="http://www.google.com" target="_blank">http://www.google.com </a> - - <h2 class="sub-heading-text" id="subHeadingText">14.01. DOM (Document Object Model)</h2> - - <ul> - <li class="list-item">DOM represents the whole html document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way</li> - <li class="list-item">The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings etc.), are related to the topmost structure: the document itself</li> - <li class="list-item">DOM defines the logical structure of the documents and the way in which they can be accessed and manipulated </li> - <li class="list-item">DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content</li> - <li class="list-item">In DOM world always think in form/terms of `Nodes` (elements, its attributes, text etc.)</li> - </ul> - - <h2>14.02. Node</h2> - As we learnt above, in DOM, all parts of the document (like elements, its attributes, text etc.) are organized in a hierarchical tree-like structure; similar to a real life family tree which consists of parents and children. In DOM terminology these individual parts of the document are known as `nodes`. <br/><br/> - There are different types of nodes like: `Elements, Attribute & Text Node`. - -<pre> - <ul id="list" --> Element & Attribute NODE - <li>first item </li> --> text NODE - </ul - - * Elements NODES not contains text -</pre> - - <h2>14.05. JavaScript DOM HTML Get Set Attributes</h2> - <ul class="normalList"> - <li>An attribute in HTML `provides extra information` about the element, and it is applied within the start tag</li> - <li>An HTML attribute contains two fields: `name & value / key & value`</li> - <li>JavaScript provides several methods for adding, reading or removing an HTML element's attribute like `setAttribute(), getAttribute(), removeAttribute()`</li> - </ul> - - <h2>14.05.03. Removing Attributes from Elements</h2> - - <ul class="normalList"> - <li>The `removeAttribute()` method is used to remove an attribute from the specified element</li> - </ul> - - </div> - - </div> - - <!-- include external JavaScript - body section --> - <script src="./14.05.03.script.js"></script> - - </body> - -</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js deleted file mode 100644 index 8cb3b1d..0000000 --- a/_examples_javascript_beginners/15. DOM (Advanced)/14. DOM/14.05.03.script.js +++ /dev/null @@ -1,22 +0,0 @@ -// external js file -// Write all JavaScript code here - -// Selecting element with id -let mainHeadingElement = document.getElementById('mainHeadingText'); -let clickButtonElement = document.getElementById('clickButton'); -let linkTextElement = document.getElementById('linkText'); - -// removing the attributes -mainHeadingElement.removeAttribute('class'); - -// verify/confirm class removed or not -console.log('mainHeadingElement.getAttribute:', mainHeadingElement.getAttribute('class')); -console.log('mainHeadingElement.classList.contains:', mainHeadingElement.classList.contains('class')); - -// console.log('// ------------------------------'); - -clickButtonElement.removeAttribute('disabled'); - -linkTextElement.removeAttribute('href'); - -// console.log('// ------------------------------'); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.js.dom.AddingClasses.html b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.js.dom.AddingClasses.html new file mode 100644 index 0000000..f3f2bb4 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.js.dom.AddingClasses.html @@ -0,0 +1,81 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>15.DOM.Advanced.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + </head> + + <body> + <div class="container"> + <div class="sub-container"> + <h1 class="heading-text" id="mainHeadingText"> + <font>15. DOM (Advanced)</font> + </h1> + + <h2 class="sub-heading-text" id="subHeadingText"> + 15.01. Dynamic DOM Manipulation + </h2> + <ul> + <li class="list-item"> + Dynamic DOM manipulation involves creating, modifying, and deleting + elements and their attributes in real-time using JavaScript. + </li> + <li class="list-item"> + Common methods include `createElement()`, `appendChild()`, + `removeChild()`, and `replaceChild()`. + </li> + <li class="list-item"> + Developers can add interactivity and dynamic content to web pages by + manipulating the DOM tree. + </li> + </ul> + + <h2>15.02. Class Manipulation</h2> + <ul> + <li> + JavaScript provides methods to manipulate CSS classes for elements + dynamically. + </li> + <li> + Methods like `classList.add()`, `classList.remove()`, + `classList.toggle()`, and `classList.contains()` are commonly used + for class manipulation. + </li> + <li> + Class manipulation helps in controlling element styles and behavior + programmatically. + </li> + </ul> + + <h2>15.03. Handling Forms and Input Fields</h2> + <ul> + <li> + DOM provides methods to interact with forms and input fields, making + it easy to capture, validate, and process user inputs. + </li> + <li> + Commonly used methods include `getElementById()`, `querySelector()`, + and event listeners like `onchange`, `onsubmit`, and `onclick`. + </li> + <li> + Dynamic form handling can be achieved by modifying the `value`, + `checked`, and `selected` properties of input fields. + </li> + </ul> + </div> + </div> + + <!-- include external JavaScript - body section --> + <script src="./15.02.01.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.script.js new file mode 100644 index 0000000..e247dc9 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.01.script.js @@ -0,0 +1,13 @@ +// Select the second <ul> +let secondUl = document.querySelectorAll("ul")[1]; // 0-based index, so 1 means the second <ul> + +// Add a class to the first <ul> +secondUl.classList.add("second-ul-class"); + +// Select all <li> children of the second <ul> +let liElements = secondUl.querySelectorAll("li"); + +// Add a class to each <li> of the second <ul> +liElements.forEach((li, index) => { + li.classList.add(`second-ul-li-${index + 1}`); +}); diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.js.dom.RemovingClasses.html b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.js.dom.RemovingClasses.html new file mode 100644 index 0000000..08534a6 --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.js.dom.RemovingClasses.html @@ -0,0 +1,81 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <meta http-equiv="X-UA-Compatible" content="ie=edge" /> + <title>15.DOM.Advanced.html</title> + + <!-- internal style --> + <style> + /* css selector: { property:value; } */ + body { + font-family: arial; + } + </style> + </head> + + <body> + <div class="container"> + <div class="sub-container"> + <h1 class="heading-text" id="mainHeadingText"> + <font>15. DOM (Advanced)</font> + </h1> + + <h2 class="sub-heading-text" id="subHeadingText"> + 15.01. Dynamic DOM Manipulation + </h2> + <ul> + <li class="list-item"> + Dynamic DOM manipulation involves creating, modifying, and deleting + elements and their attributes in real-time using JavaScript. + </li> + <li class="list-item"> + Common methods include `createElement()`, `appendChild()`, + `removeChild()`, and `replaceChild()`. + </li> + <li class="list-item"> + Developers can add interactivity and dynamic content to web pages by + manipulating the DOM tree. + </li> + </ul> + + <h2>15.02. Class Manipulation</h2> + <ul class="second-ul-class"> + <li> + JavaScript provides methods to manipulate CSS classes for elements + dynamically. + </li> + <li> + Methods like `classList.add()`, `classList.remove()`, + `classList.toggle()`, and `classList.contains()` are commonly used + for class manipulation. + </li> + <li> + Class manipulation helps in controlling element styles and behavior + programmatically. + </li> + </ul> + + <h2>15.03. Handling Forms and Input Fields</h2> + <ul> + <li> + DOM provides methods to interact with forms and input fields, making + it easy to capture, validate, and process user inputs. + </li> + <li> + Commonly used methods include `getElementById()`, `querySelector()`, + and event listeners like `onchange`, `onsubmit`, and `onclick`. + </li> + <li> + Dynamic form handling can be achieved by modifying the `value`, + `checked`, and `selected` properties of input fields. + </li> + </ul> + </div> + </div> + + <!-- include external JavaScript - body section --> + <script src="./15.02.02.script.js"></script> + </body> +</html> diff --git a/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.script.js b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.script.js new file mode 100644 index 0000000..4dc207d --- /dev/null +++ b/_examples_javascript_beginners/15. DOM (Advanced)/15.02.02.script.js @@ -0,0 +1,5 @@ +// Select the second <ul> +let secondUl = document.querySelectorAll("ul")[1]; // 0-based index, so 1 means the second <ul> + +// remove class "second-ul-class" <ul> +secondUl.classList.remove("second-ul-class");