Articles by "JavaScript"
Showing posts with label JavaScript. Show all posts
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

In the previous chapter of JavaScript, we have learned the method to target the HTML Element. Now we are about to move on 'How many possible ways are there to display output in JavaScript?'

Although JavaScript executes many of task that has no concern with the display but most of the times different types of JavaScript output data required to display on browser.

JavaScript can display output data in different ways. Below are the properties, methods, and functions that can be used to display output data in JavaScript.

  1. Using innerHTML property
  2. Using innerText property
  3. Using textContent property
  4. Using document.write() method
  5. Using alert()
  6. Using console.log()
  7. Using print()

Using innerHTML property

The innerHTML property is part of the Document Object Model (DOM) that allows JavaScript code to manipulate a website being displayed. Specially it allows reading and replacing everything within a DOM Element (HTML tag).

The innerHTML property can output the data in the form of HTML content. You check in the example.


Code Copied
<script>
    document.write(document.getElementById("test").innerHTML);
</script>
Try Yourself

Using innerText property

The innerText property sets or returns the text content of the specified node and all its descendants.

If innerText property is used then child nodes are removed and replaced by a single text node.


Code Copied
<script>
    document.write(document.getElementById("text").innerText);
</script>
Try Yourself

Using textContent property

The textContent property us similar to the innerText property of JavaScript but there is a difference between them. We will discuss those differences later in this article.


Code Copied
<script>
    document.write(document.getElementById("text").textContent);
</script>
Try Yourself

Using document.write() method

The document.write() is a method which writes a string of text to document stream. The write() method writes HTML expression or JavaScript code to a document. The write() method is used for testing purposes mostly.

If document.write() method is used after fully loaded HTML page then it will override all the existing HTML and gives new HTML Page.


Code Copied
<script>
    document.write(document.getElementById("text").textContent);
</script>
Try Yourself

Using alert()

The alert() method in JavaScript displays an alert box with a specified message along with an 'OK' button. It is often used to make sure that information comes through the user. The alert() box takes the focus away from the current window and forces the browser to read the message.


Code Copied
<script>
    function getAlert(){
        alert(document.getElementById("test").innerHTML);
    }     
</script>
Try Yourself

Using console.log()

The console.log() is a function in JavaScript that is used to print any kind of variables defined before console.log()or to just print any message that needs to be displayed to the user.

console.log() is used for debugging purposes we can call the console.log() method in the browser to display data.


Code Copied
<script>
    console.log(document.getElementById("test").innerHTML);        
</script>
Try Yourself

Using print()

JavaScript print method is used to print the contents of the current window. It basically opens a print dialog box in the browser.


Code Copied
<script>
    function getPrint(){
        print();
    }         
</script>
Try Yourself

What is the difference between innerHTML, innerText, and textContent?

innerHTML property allows us to work with rich text and doesn't automatically encode and decode text. We can get the data to display in a rich text format where CSS can also work.

innerText property retrieves and sets the content from the HTML tag as plain text where spaces are trimmed in results but the CSS styling can be displayed in results. 

textContent property retrieves and sets the content similarly innerText but spaces and whitespace cannot be trimmed and CSS styling cannot be displayed in results.

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

ID and Class attributes are the most common selectors that widely used to target the HTML DOM while working with JavaScript. Have you ever thought why we mostly prefer to use the id and class while many of the methods are available to target the HTML Elements in JavaScript?

First of all, we look at all the methods to target the HTML Elements using JavaScript.

For reference you can check the multiple examples below.

How to target HTML elements using ‘id’?



    <div id="test"></div>
    <script>
        //we want to print "Hello World inside div"
        document.getElementById("test").innerHTML="Hello World!";
    </script>
Try Yourself

In this method we target the Single HTML element within the DOM tree using its ID attribute. While using ID, it always returns a single node of HTML DOM.

The most important thing is that using two or more HTML elements with the same ID on the same web page can produce the unexpected error, therefore, we should be careful using the ID attribute while creating the web page.

How to target HTML Elements using ‘class’?



    <!--Different HTML tags with same classes-->
    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    
    <script>
        document.getElementsByClassName("test")[0].innerHTML="This Heading";
        document.getElementsByClassName("test")[1].innerHTML="This is div";
        document.getElementsByClassName("test")[2].innerHTML="This is paragraph";
        document.getElementsByClassName("test")[3].innerHTML="This is span";
    </script>
Try Yourself

In this method we target one or more HTML Elements with the same class name. When we target HTML Elements with the class name, each HTML element with the same class becomes the part of that class, it returns a list of nodes (referred to as NodeList in the console) instead of a single node where each node can be referred with the index number like given in above example.

The index number of each node is decided by its appearance on the web page. For e.g. the index of the very first node is referred to as [0] and second as [1] and so on. If the position of any node is changed on the webpage then its index will be also changed accordingly and it might affect the index of rest upcoming nodes also.

Even we target a single element with the class name, it returns a list of nodes but the difference is that there is only a single node present in that list.

Therefore it is a better idea to use class names but in a structured way.

We will study more about classes in further chapters

How to target HTML Elements using ‘tag name’?



    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    <span class="test"></span>
    <script>
        document.getElementsByTagName("H1")[0].innerHTML="This Heading";
        document.getElementsByTagName("DIV")[0].innerHTML="This is div";
        document.getElementsByTagName("P")[0].innerHTML="This is paragraph";
        document.getElementsByTagName("SPAN")[0].innerHTML="This is first span";
        document.getElementsByTagName("SPAN")[1].innerHTML="This is second span";
    </script>
Try Yourself

In this method we target one or more HTML elements with their tag name. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

How to target HTML Elements using the ‘name’ attribute?



    <!--Different HTML tags with same classes-->
    <form action="">
        <div><input type="text" name="fname" placeholder="first name" value="John"/></div><br/>
        <div><input type="text" name="lname" placeholder="last name" value="Doe"/></div><br/>
        <div><input type="email" name="email" placeholder="email" value="john@progrramers.com"/></div><br/>
        <div><input type="url" name="website" placeholder="website" value="https://progrramers.com"/></div><br/>
        <div><input type="button" name="submit" value="Save" onclick="formdata()"/></div><br/>
    </form>
    <p name="test"></p>
    <script>
        function formdata(){
            var fname=document.getElementsByName('fname')[0].value;
            var lname=document.getElementsByName('lname')[0].value;
            var email=document.getElementsByName('email')[0].value;
            var website=document.getElementsByName('website')[0].value;
            document.getElementsByName("test")[0].innerHTML = "First name: "+fname+"<br/>Last name: "+lname+"<br/>Email: "+email+"<br/>Website: "+website;
        }
    </script>
Try Yourself

In this method we target one or more HTML elements with their name attribute. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

Note: Name attribute’s value also can be accessible in the post method of server-side scripts like PHP. We will deal with it during the tutorials of server-side scripts.

How to target HTML Elements using the ‘querySelector’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelector('#test_id').innerHTML="This is First DIV Element.";
        document.querySelector('.test_class').innerHTML="This is Second DIV Element.";
    </script>
Try Yourself

In this method we target single HTML Element using CSS selector. In CSS if we want to target element with tag name we use the tag name, or if we want to use the ID or Class then we use ‘#’ with ID and ‘.’ with the class name. Similarly we can use CSS all selector to with query selector method.

Likewise ID case, it returns only the first node present on the web page.

How to target HTML Elements using ‘querySelectorAll’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelectorAll('#test_id')[0].innerHTML="This is First DIV Element.";
        document.querySelectorAll('.test_class')[0].innerHTML="This is Second DIV Element.";
        document.querySelectorAll('.test_class')[1].innerHTML="This is Third DIV Element.";
    
        console.log(document.querySelectorAll("DIV"));
    </script>
Try Yourself

This method is the same as the query selector method but in this method we target one or more HTML Elements using CSS selector and it returns a set the node list where each node can be accessed by the specific index number.

You have seen all the examples given above. These are the methods to target the HTML DOM or HTML DOMs in JavaScript. You must know a few things also which are mentioned below

  1. The methods that return the list of nodes can be looped. Check example 7 ahead.
  2. Although node list can be looped they aren’t referred to as an array because array must have few methods like push, splice & sort but not in case of node list.
  3. ID, Class, and Name are the attributes that can be directly accessed in JavaScript. For reference Check example 8.
  4. Id & name attribute can have one value at a time and can be used only once on the webpage but the class can have multiple values at the same time. The value should be separated by space. For e.g. class=”container box primary”. There are three different classes in the example container, box & primary.

How to apply loop on a NodeList?


Code Copied
<div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <script>
        var el=document.querySelectorAll('.test'),n=1;
        el.forEach(element => {
            element.innerHTML="This is DIV No. "+(n++);
        });
    </script>
Try Yourself

How to Find ID, Class & Name Attribute Values?


<div id="test_id">This DIV has id Attribute</div>
    <!--Class can have multiple value-->
    <div class="test_class1 test_class2 test_class3">This DIV has class Attribute</div>
    <div name="test_name">This DIV has name Attribute</div>


    <p id="result_1"></p>
    <p id="result_2"></p>
    <p id="result_3"></p>

    <script>
        document.getElementById("result_1").innerHTML = document.getElementById("test_id").id;
        document.getElementById("result_2").innerHTML = document.getElementsByClassName("test_class1")[0].className;
        document.getElementById("result_3").innerHTML = document.getElementsByName("test_name")[0].getAttribute("name");
    </script>
Try Yourself
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

In the previous chapter of JavaScript Tutorials, we have learned about what JavaScript can do? Now we are about to learn that How and Where to use JavaScript on an HTML Document?

How to use JavaScript on HTML Documents?

Before we go forward we need to understand the most important thing and that is ‘How a web page is parsed on a web browser? This question is most important because until unless we don’t understand the working principle of a webpage, we can’t develop it with any client-side scripting language like JavaScript.

We already know that JavaScript manipulates the HTML DOM by changing its inner HTML, inner Text, values, and style. JavaScript is used to perform a certain task or chain of the task and execute it on the browser by changing the status of HTML DOMs. To do so we have to find and target the specific HTML DOM with various methods that we will learn in upcoming chapters. 

To understand the above sentences we need to check the below example.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of JavaScript</title>
</head>
<body>
    <div id="test"></div>
    <script>
        document.getElementById("test").innerHTML = "Hello World!";
    </script>
</body>
</html>
        
Try Yourself

What we see in the example above given. There are two things in the above example

The first thing we see there is an HTML document contains a DIV element with an attribute named ID. The value of the ID is ‘test’. We required printing Hello World inside the DIV element dynamically using JavaScript when a web page is loaded.

Second thing, there is also a script tag just before the end of body tag where are some codes are written which is not likely HTML codes. Actually the codes written in script tags are JavaScript. JavaScript codes are written between <script> tags on HTML documents.

Now to understand the working principle of the above example you can copy and paste the above code in your favorite HTML editor and save the file with .html file extension and run into your favorite browser. You will see ‘Hello World’ printed on the web page.

On the web page loading process, we simply target the HTML DIV tag by its ID using “document.getElementById()” method and setting the value ‘Hello World’ of its ‘innerText’ so that when the web page completely falls on the browser it prints ‘Hello World’ text.

This is how we target the HTML DOM on an HTML web page using JavaScript. This was only an example but in professional projects, we do something like this on a large scale. We will sure study that in this tutorial series.

 

Why & when use type attribute within <script> tags?

Now we know that JavaScript codes are written inside <script> tags. Let’s check a few another example given below

JavaScript codes with a type attribute in script tags


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Use of Type Attribute</title>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
    </script>
</body>
</html>
        
Try Yourself

JavaScript codes without type attribute in script tags


<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Example of HTML5 Version Doctype</title>
</head>
<body>
     <div id="test"></div>
     <script>
          document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
     </script>
</body>
</html>
Try Yourself

In both examples can you see the difference? You can see in example 2 <script> tag is used with type attribute and in example no 3 <script> tag is used without type attribute.

This is happening because of the HTML Document version. Before HTML version 5 JavaScript is not the default scripting language of HTML so we must specify the type of scripting language. Older browsers are not able to find the type of script language therefore JavaScript might not work.

But since HTML 5th version JavaScript is becoming the default scripting language, therefore, we are not forced to use type attribute in script tag while working with JavaScript.

Note: Above both examples can work in the latest browsers without type attribute. The problem comes with only older browsers.

Where to use JavaScript on HTML Documents?

Above all the examples are demonstrating to us how to use JavaScript on an HTML Document. Now let’s move on Where to use JavaScript on HTML Documents?

Before we go ahead first we need to understand how an HTML Document is parsed on a browser and become a web page.  Usually, HTML Document is parsed on a browser top to bottom and left to right. It means that the most top line of the document is parsed first into left to right direction therefore whole HTML DOMs must be parsed over web browsers before JavaScript functions are called.

If it doesn’t happen then the browser console will throw the script error and it can be case wise different. Another thing is that by default JavaScript declared functions and variables are stored on the top level in primary memory while launching the web page whether they are declared on top of page or bottom of the page, therefore, we should not worry about where we are trying to keep our JavaScript codes on HTML document. Therefore we can place JavaScript declared functions and variable between the <head> tags like the below-mentioned example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Declared Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button onclick="myFunction()">Click</button>
</body>
</html>
        
Try Yourself

We should worry about only JavaScript calling functions which must be executed at the most end of part of the web page so that All HTML DOMs can found easily found which are targeted by JavaScript. It is good practice to place JavaScript codes on the most bottom part of HTML <body> tags, mention like below example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Calling Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>

    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        
Try Yourself

Also, it is observed that placing JavaScript code at the bottom of <body> tags improves the display speed because script interpretation slows down the display.

Above shown examples are a type of internal JavaScript but there is another type of JavaScript also which can improve the development speed without harming the performance of the web site.

What are the types of placement of JavaScript on an HTML Document?

  1. Internal JavaScript
  2. External JavaScript

What is Internal JavaScript?

Internal JavaScript is a practice in which all the JavaScript codes are written separately in every document. The drawback of this practice is that we have to write a similar type of code again and again which slows down the development speed. All the above show examples are a type of internal JavaScript.

What is External JavaScript?

In this practice JavaScript codes are written in a separate file which has the file extension “.js”. To embed the external JavaScript file on the web pages we have to use <script> tags with a specific attribute named ‘src’ which holds the location path of the external JavaScript file.

Take a look at a below-given example. This example is created using jQuery CDN. You will learn jQuery in further chapters.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Absolute Path Over jQuery Content Delivery Network (CDN)</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        $(document).ready(function(){
            $('#test-button').click(function(){
            $('#test').html("Hello World!")
            });
        });
    </script>
</body>
</html>
        
Try Yourself

Few points must be noticed while creating an external JavaScript file.

  1. JavaScript file created with .js extension is not a web page rather a script page.
  2. JavaScript file cannot contain the <script> tags.
  3. Multiple JavaScript pages can be used on a single HTML document.
  4. It is important to declare the HTML web page doctype because before HTML5 JavaScript not default scripting language. We have to specify the ‘type’ attribute in <script> tags to make active scripting language.

What are the advantages of external JavaScript?

  1. HTML and JavaScript codes are separated while using external JavaScript
  2. JavaScript code which required to be executed again & again on different pages is not required to write multiple times.
  3. It makes developers easy to maintain and develop the program fast.
  4. You can use different specialist code editor at the same time. For example, Notepad++ is best for HTML, and VSCode is best suitable for JavaScript.
  5. External JavaScript code can be cached into the client device therefore cached JavaScript file can speed up the page load.

Using absolute and relative path reference for external JavaScript

 External JavaScript files can embed on HTML documents using relative or absolute path references which show below in the examples.

To understand relative or absolute file path learn HTML5 Tutorial - HTML File Path


//declared functions and variables
  var x = "You have clicked the button."
  function myFunction(){
  document.getElementById('test').innerHTML=x;
}
        


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of External JS file using absolute path</title>
    <script src="script.js"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        

Copy the JavaScript codes given in example 7 and paste into your favorite text editor and save as script.js and after that once again create a new file in the text editor and copy HTML codes from example 8 and paste into the text editor and save the document as 'example8.html'. Both the files must be located into same directory. 

After that run the example8.html file in the browser, you will see on the web page there is a button named 'Click'. When you click the button then a sentence 'You have clicked the button' will appear on the screen. This means the JavaScript codes written in a separate file is embedded properly and working fine.

On HTML file example8.html you can see <script> tag with 'src' attribute having the value 'script.js' which the name of JavaScript file. Actually the source of JavaScript is fetching on the web page from that file which is embedded with HTML document through a 'Relative path'.

Similarly, look back into example 6 where you can find <script> tag with 'src' attribute having a value 'https://code.jquery.com/jquery-3.5.1.min.js'. It is an example of an absolute URL. To know more about the relative and the absolute path you have to read our another topic HTML5 Tutorial - HTML File Path.

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello programmers! This is a new “JavaScript How To” post which describes ‘How to create Cascading Dropdown Using Plain JS’. This is an example of multiple dependent dropdown lists. Multiple dependent cascading dropdown lists are very useful when you want to display the data in specific categories. You can change drop down options based on another dropdown lists.

First of all, you can click on Try yourself button in below example and check what are we going to create and after that you will find all the require source code of this project. You can also bookmark the repository of progrramers GitHub community where you can find and download the source code of other projects.
If you like our posts please give thumbs up  👍 on our Facebook page and also share with your near n dears.



Diagram

In this example we are assuming that there is a school. It has multiple class rooms, every class room contains multiple sections, every section contains multiple subjects and at last every section period will held on a different room. You can see the whole scenario in below image given for the reference.

How to create Cascading Dropdown Using Plain JS - progrramers
How to create Cascading Dropdown Using Plain JS - progrramers

The data will be in tree structure which is used to parse as options in 'SELECT' elements. Let's see the work flow of the final product.

Work Flow 

  1. Classes names only append into select element onload first.
  2. When Selecting a Class then section options will append, available with that class. Same work flow for sections, subjects and rooms.
  3. When Class gets changed then sections, subjects and rooms also get reset. Same work flow for sections, subjects and rooms. Synopsis when a drop down element updated then all next siblings also gets reset.
Now you can copy the code and paste it into your favorite editor and save as ‘anyname.html’ and run into your favorite browser. Analyze the code and if you are getting any problem then feel free to write down into the comment section I’ll try to be more specific into the answers.

You can also get this code on github : How to create Cascading Dropdown Using Plain JS.html

How to create Cascading Dropdown Using Plain JS :

<!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>Document</title>
    <style>
        *{box-sizing: border-box;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
        .classform{border: 5px groove #00acf0;background: #c5c5c5;border-radius: 4px;}
        div{padding:5px;}
        .classform>div{width:450px;display:block;margin-left:auto;margin-right:auto;}/*for responsive look*/
        label{background: #00acf0;color:rgb(255, 255, 255);text-shadow:1px 1px 1px #777}
        label,select{display:inline-block;padding:6px;border-radius:3px}
        label{width:100px;}
        select{width:250px;}
    </style>
</head>
<body>
    <div class="classform">
        <div><label for="class">Class: </label> <select name="class" id="class"></select></div>
        <div><label for="section">Section: </label> <select name="section" id="section"></select></div>
        <div><label for="subject">Subject: </label> <select name="subject" id="subject"></select></div>
        <div><label for="room">Room: </label> <select name="room" id="room"></select></div>
    </div><hr/>
    <a href="https://www.facebook.com/theprogrramers">Follow us on Facebook Page</a>
    <script>
        //class structure data in JS object format
        var structure = [
                {label:"class",value:"1",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                ]},
                {label:"class",value:"2",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Sanskrit",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"English",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Civics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Geography",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Economics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (C)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (D)",child:[]},
                        ]}
                    ]}
                ]},
                {label:"class",value:"3",child:[
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"3 (A)",child:[]},
                        ]}
                    ]}
                ]},
            ];
        //global variable declaration to store value stepwise
        var cindex, sindex, jindex;
        //calling funfction onload
        window.onload = function(){
            classstrucure(structure, document.querySelectorAll('[name=class]'));
        }
        document.querySelector('body').addEventListener('change',function(e){
            if(e.target.tagName.toLowerCase() == "select"){
                if(e.target.value!==""){
                    //check of nextsibling is null or not 
                    nextsibling = e.target.closest('DIV').nextSibling.nextSibling;
                    if(nextsibling!==null){
                        var _nameAttr=e.target.getAttribute("name");
                        var nextElm = nextsibling.querySelectorAll('SELECT');
                        //for your project only you have to change the attributes name
                        if(_nameAttr==='class'){
                            cindex = structure.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='section'){
                            sindex = structure[cindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='subject'){
                            jindex = structure[cindex].child[sindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child[jindex].child, nextElm);
                        }
                    }
                }else{
                    //e.target.value is empty then same function will fire with defferent parameters
                    clearsturcture(e.target.closest('DIV').nextSibling);
                }
            }
        });
        //function create the structure of class step wise
        function classstrucure(data, el){
            //first clear all the select element onload
            //clear all next sibling accept itself
            el.forEach(element => {
                clearsturcture(element.closest('DIV')); 
            });
           // clearsturcture(el[0].closest('DIV'));            
            var opt = '<option value="">--Select--</option>';
            //creating options elemnet
            for(var i=0;i<data.length;i++){
                opt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
            }
            //appending option on each element
            el.forEach(element => {
                element.innerHTML = opt;
            });
        }
        //clear all the next drop down element after itself
        function clearsturcture(parentEl){
            while (parentEl) {
                if(parentEl.tagName !== undefined){
                    //appending initial option on every next sibling
                    parentEl.querySelector('SELECT').innerHTML = '<option>--Select--</option>';
                }
                //looping through last existing sibling and target
                parentEl = parentEl.nextSibling;
            }
        }
    </script>
</body>
</html>
Try Yourself

Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is HTML DOM?

When a web page is loaded, the browser creates a Document Object Model of the page.
The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
The HTML DOM is a standard object model and programming interface for HTML. It defines:
  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements


What is HTML DOM - progrramers exlained
HTML DOM TREE STRUCTURE



What is HTML DOM Event?

HTML DOM Events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).


What is HTML DOM Event? Explanation Image
HTML DOM Event

What is an EventListener?

An event listener is a procedure or function in a computer program that waits for an event to occur. For examples - the user clicking or moving the mouse, pressing a key on the keyboard, or an internal timer or interrupt are events.

What is Dynamic HTML DOM?

An HTML DOM or DOM tree created with the combination of HTML and JavaScript after page loaded is referred as Dynamic HTML DOM. Dynamic HTML can be created after when the client side scripting language event occurred. For example – document.createElement(TAGNAME);

What is Event delegation?

Event delegation is the process of handling events at a higher level in the DOM that where they were first triggered, thanks to behavior known as Bubbling. For example - when an element on the page is, clicked, then a click event is fired on that element but it doesn’t stop there. The click event “bubbles up” the DOM tree, triggering the click events on any of the originally clicked element’s parents that are listening for one.

What is bubbling?

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.

What is bubbling
HTML DOM Event : Image courtesy W3.org


Above image describe the three phase of HTML DOM Event:
  • Capturing – The event goes down to the element (very rare use)
  • Target – The event reach the target element
  • Bubbling – The event bubbles up from the element

Why EventListeners don’t work on Dynamic HTML DOM?

HTML DOMs created dynamically don’t have its own Event Handlers because they aren’t static part of the DOM tree hence simple EventListeners cannot target it to fire the function but they are part of the loaded document, therefore to handle the events, we have to use Event Delegation to the HTML Elements appended dynamically.
Next post will elaborate “How to Create Event Listeners for Dynamic HTML DOM?”

Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
In previous chapter of Java Script we have learnt that what Java Script is and taken the brief introduction of what can Java Script do?

Now we are going to study more descriptively that what Java Script can do and how?

What Java Script can do?


Java Script can change the HTML element, HTML Element contents, style and attribute values. Java Script finds the HTML element by many methods. Most frequently used method is ‘getElementById()’ method.

getElementById() method


In this method Java Script find the HTML element by their ‘id’ attribute value. For example


<p id = "test"></p>
<script>
  document.getElementById('test').innerHTML = 'Hello World!';
</script>

Note : Java Script accepts both single quotes (‘ ’) and double quotes (“ “).

Java Script can Hide and Show the HTML elements


Java script can hide the HTML elements and show the elements as well by changing the element style (CSS). So we can also say that Java script can change the style of HTML elements.

This is how you can hide the HTML element.


<p id = 'test'>This paragraph is not displayed on the web page if you click below button.</p>
<button onclick = "document.getElementById('test').style.display = 'none';">Hide</button>

And this is how you can show the hidden element.


<p id = 'test'>This paragraph is not displayed on the web page if you click below button.</p>
<button onclick = "document.getElementById('test').style.display = 'block';">Show</button>

Note: You must be familiar with CSS to understand above example.

Java Script can change the value of attribute


Java script can change the value of HTML element attribute. In below example image source is change by Java Script function.


<button onclick = "document.getElementById('myImg').src = 'raincloud.png'">Rainy</button>
<img src = "cloud.png" width = '60%' id = "myImg" onclick = "cloud()">
<button onclick = "document.getElementById('myImg').src = 'cloud.png'">Sunny</button>

Java Script can Add or Remove the HTML elements


Java Script can add and remove the HTML elements. Check the example how to add the HTML element using java script.


<div id = "test">
  <p>Click the below button to create a new paragraph.</p>
</div>
 <button onclick = "createlem()">Create</button>
 
 <script>
  function createlem(){
   var para = document.createElement('p');
   var text = document.createTextNode('This is new paragraph.');
    para.appendChild(text);
   var elem = document.getElementById('test');
    elem.appendChild(para);
  }
 </script>

This is how Java Script can remove HTML element.


<div id = "elem_parent">
<p id = "elem_childe">Click the below button to remove existing paragraph.</p>
</div>
<button onclick = "delelem()">Remove</button>
 <script>
  function delelem(){
   var elem_parent = document.getElementById('elem_parent');
   var elem_childe = document.getElementById('elem_childe');
   
   elem_parent.removeChild(elem_childe);
  }
 </script>


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is Java Script?

Java Script is an open and cross platform lightweight, interpreted dynamic programming language of HTML. It is designed for creating network-centric applications. It is performed on client’s devices.
Java Script is very easy to learn. Also it is very easy to impalement because it is integrated with HTML and Java but Java Script and Java are completely different language in regards of concept and designed.

Java Script is developed by Brendan Eich in 1995, it was first known as LiveScript and latter Netscape change its name to Java Scrip. It became an ECMA Standard in1997. ECMA-262 is the official name of the standard and ECMAScript is official name of the language. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.


My first Java Script

Click the button

What should you know before learning Java Script?

To learn Java Script you must have the knowledge of HTML coding. Java Script can manipulate the CSS codes along with the HTML therefore it is better to learn HTML and CSS before starting Java Script.



This is the Java Script Example - Changing the HTML Element and CSS

Click the Button to change the color of below paragraph.



Why learn Java Script?


If you want to be a web developer then you must learn three languages and Java Script is one of the three languages.

1. HTML – Defines the structure and contents of the web pages.
2. CSS – Defines the Layout and the style of the web pages.
3. Java Script – Defines the behavior of the web pages.


What Java Script can do?


Java Script can change the HTML Contents, Elements, Attributes, and Style etc. It can remove or create HTML elements and make contents visible or hidden on a web page. Java Script can manipulate HTML and CSS code.



This is the Java Script Example - Changing the HTML Element and CSS

Click below paragraph to change the color.

Java Script Tutorials - Introduction
Java Script Tutorials - Introduction