JavaScript createElement

JavaScript createElement

In this lesson we study JavaScript createElement method, useful to create new elements in the DOM.

In the previous article we saw how to manipulate the DOM in JavaScript and studied methods for selecting elements on a page. You can consult the article at the following link: https://www.codingcreativo.it/en/javascript-dom/.

JavaScript createElement – How to create elements in the DOM

The element to create can be, for example, a new level, a new paragraph, a new title, etc.

To create elements in the DOM in JavaScript we will use the createElement() method, specifying the type of element you want to create inside the brackets.

The syntax is therefore this:

element = document.createElement(tag);

where tag can be any tag.

To add the new element, at the end of the list of elements contained in the current node, we use the appendChild() method.

JavaScript createElement – first example

So let’s see a practical example of how to create elements in the DOM with JavaScript.

If you try clicking the button below, a new item will appear.

In this point I insert the button:

For the development of this example, we first create a new layer (div) with id equal to button, which corresponds to the point where the new button will appear.

Here I will insert the button:

<div id="button">In this point I insert the button: </div>

Below we insert the button to which the onclick event is associated which calls the insert() function.

<input type="submit" onclick="insert()" value="insert">

We then create the insert() function in JavaScript.

This function will create a new button, with JavaScript createElement method, which will contain the word Scratch. Then we insert the element, using the appendChild () method, into the layer with the same id as the button.

So here’s the JavaScript code:



function insert() {
  var btn = document.createElement("button");
  btn.innerHTML = "scratch";
  document.getElementById("pulsante").appendChild(btn);
}

Conclusion

In this tutorial we have introduced the createElement JavaScript method, in the next lessons we will study other methods to manipulate the DOM.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript DOM

JavaScript DOM

In JavaScript it is possible to manipulate the DOM. In these lessons we will learn for example how to create new elements, add attributes or even delete elements in the HTML DOM.

The web browser, when it loads the web page creates the DOM (Document Object Model).

The DOM can be seen as a tree structure, such as this:

dom javascript

So, the DOM structure of this web page is therefore:

document

      head

           title

                title of the document (text node)

     body

         p

              paragraph text (text node)

        h1

              title (text node)

JavaScript DOM – How it uses

In JavaScript, by manipulating the DOM, you can add or remove existing elements and attributes, and you can also create new events on a page.

The root of the document, i.e. the web page, is represented by document. The document object is therefore the father of all other elements.

Let’s consider that you can access the elements directly, that is, without going through the entire tree.

Element is a node that represents an html element (a tag), while text is the last child node of a parent and represents a text node.

JavaScript DOM – Document methods for selecting elements on a page

We continue the tutorial JavaScript on the DOM by presenting in particular the methods of the document object to select elements.

JavaScript DOM – getElementById()

The getElementById () method identifies an element on the page through the id associated with an html tag.

So let’s take an example.

Try to click the button below, you will notice that the writing will change.

Click on the button to try getElementById.

Click on the button to try getElementById() method.

First of all, I insert a level with the div tag to which I associate the change id. Then I insert a button where I add the onclick event, to which I associate the change () function which has the purpose of changing the text contained within the div tag.

I also use the innerHTML property to change the text.

<div id="change">Click on the button to try getElementById() method.</div>
<button onclick="change()">Change</button>
<script type="text/javascript">
function change() {
  document.getElementById("change").innerHTML="Welcome on Coding Creativo";
}
</script>

JavaScript DOM – getElementsByClassName()

In JavaScript to manipulate the DOM we have another method that allows us to identify the elements of a web page based on the associated class, namely the getElementsByClassName () method.

Let’s take an example in order to understand how it works.

If we click on the button below, the last item in the list will be modified and all the elements to which the code class is associated will be given a blue background and white writing.

Scratch
Algobuild
C language
C++ language

I explain the procedure:

First of all I created a series of levels all with the same class in which I wrote the names of the programs. I want when I click the button, the last item changes and also all the layers turn light blue and the writing color turns white.

After I insert the button with the onclick event that calls the coding () function.

In JavaScript then I construct this function in such a way as to take the element with index 3 to which the code class is assigned and in place of the previous content it replaces the Java text.

In addition to all the elements of class code, as mentioned before, I change formatting.

I attach the JavaScript and html code:

<div class="code">Scratch</div>
<div class="code">Algobuild</div>
<div class="code">C language</div>
<div class="code">C++ language</div>

<button onclick="coding()">Change</button>

<script>
function coding() {
  document.getElementsByClassName("code")[3].innerHTML = "Java";

var list = document.getElementsByClassName("code");
for (var i = 0; i < list.length; i++) {
  list[i].style.backgroundColor = "#f67f92";
  list[i].style.color = "#fffff";
} 
}
</script>

JavaScript DOM - getElementsByTagName()

We continue the JavaScript dom tutorial by introducing another method for selecting elements, the getElementsByTagName () method.

This method allows you to identify the elements of a web page by the name of the tag.

Let's take an example now.

If we click the change button, a blue background will be set for all the writing, except for the text outside the div.

Scratch

Text outside the div....

Algobuild
C language
C++ language
Click on the button to try getElementsByClassName().

To create this example, first of all we insert a main level to which we assign an id codingC and inside we will insert other levels and a paragraph.

As mentioned before, we want to give all divs the same formatting, while the paragraph must keep the original formatting.

So in JavaScript I create a coding () function that takes the list of the elements of div that are inside the tag with id equal to codingC and assigns them a custom background.

<div id="codingC">
  <div class="code">Scratch</div>
  <p> Text outside the div....</p>
  <div class="code">Algobuild</div>
  <div class="code">C Language</div>
  <div class="code">C++ Language</div>
</div>

<div id="cambio">Click on the button to try getElementsByClassName().<div>

<button onclick="coding()">Change</button>

<script type="text/javascript">
function coding() {

var el= document.getElementById("codingC");
var list = el.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
  list[i].style.backgroundColor = "#a5cff3";
} 
}
</script>

If we wanted to include the paragraph as well, we would just have to change this line of code:

var list = el.getElementsByTagName ("div");

and then indicate

var list = el.getElementsByTagName ("*");

where the asterisk indicates all elements.

Conclusion

This article is just a small introduction to DOM in JavaScript, we will continue in the next tutorial to explore other methods and events.

Finally we point out the w3schools website for the JavaScript DOM: https://www.w3schools.com/js/js_htmldom_events.asp.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

callbacks in JavaScript

callbacks in JavaScript

In this lesson I propose some examples of the use of callbacks in JavaScript.

I have already covered these callback functions in the following articles:

  1. JavaScript functions and return
  2. JavaScript Callback
  3. Callbacks
  4. Array method and callback functions

callbacks in JavaScript – examples

We create functions for calculating the area of ​​the rectangle and the area of ​​the triangle. Both functions return a return value that corresponds to the area of ​​our geometric figure.

Then we create a new area function to which we will pass two arguments representing the base and height of our geometric figures and a third argument which is our callback function. The function must be passed without round brackets, as we have said several times in previous lessons.

This function returns the same callback function called on the two parameters x and y.

We call up the area function once to calculate the area of ​​the rectangle, another time to calculate the area of ​​the triangle.

First we make the example with constant values, then we will insert them via a simple prompt.

Below is the complete code for our first example on callback functions:



alert('The area of ​​the rectangle is ' + area(5, 15, areaRect));
// calls the function area with 3 arguments of which the last is the callback function
alert('The area of ​​the triangle is ' + area(5, 15, areaTriangle));

var num1 = parseInt(prompt('Insert number 1'));
var num2 = parseInt(prompt('Insert number 2'));
alert('The area of ​​the rectangle is  ' + area(num1, num2, areaRect));
alert('The area of ​​the triangle is  ' + area(num1, num2, areaTriangle));

//**** functions ****//
function area(x, y, callback) {
    return callback(x, y);
}

function areaRect(a,b) {
  return a * b;
}

function areaTriangle(a,b){
    return a * b / 2;
}

callbacks in JavaScript – second example

In this second example we use a simple greeting function which is used to display the greeting via an alert.

Next we create a dataIntput function that takes a callback function as an argument. This function will ask to take data as input which will then pass to the same callback function.

We then call our dataInput function to which we will pass the greeting function as an argument.

This example is very convenient especially if we need to modify the alert with a console.log or a getElementById, for example. This way I don’t touch the main function but just change the greeting function to show a different type of output.



dataIntput(greeting);

function greeting(name, lastname) {
  alert('Welcome ' + name + ' ' + lastname);
}

function dataIntput(callback) {
  var n = prompt('Insert name');
  var c = prompt('Insert lastname);
  callback(n,c);
}

Conclusion

In this lesson I have proposed some examples on callbacks in JavaScript, I will return soon to propose many other exercises.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript setTimeout

JavaScript setTimeout

JavaScript setTimeout is a method that allows you to call a function after a certain period of time, expressed in milliseconds.

The syntax of this method is: setTimeout(function, milliseconds, p1, p2, …).

Both milliseconds and p1 and p2 are optional parameters.

The mandatory function will be executed after the time indicated in milliseconds has elapsed, otherwise after 0 seconds, if this parameter is not specified. Therefore 0 is the default value.

JavaScript is not multi-threaded but single-threaded, meaning it can only execute one task at a time at any given time.

The JavaScript engine then executes the code from top to bottom, therefore it is said to be synchronous. Through callbacks, promises and methods such as setTimeout, JavaScript performs asynchronous activities.

In addition to the JavaScript engine, the web browser also has Event Loops, Call Stacks and Web API as components.

When we use setTimeout, the JavaScript engine inserts the execution context it creates into the Call Stack. This creates a timer in the Web API component of our web browser. When time elapses, the callback function, passed as an argument to the setTimeout method, is placed in a queue.

The event loop checks both the stack and the queue, removes the callback function from the queue, puts it on the stack and then the function is executed.

JavaScript setTimeout – first example

We realize two functions quote and other quote.

The first is a function that contains the setTimeout method which has as its first parameter a callback function that simply activates an alert with a famous quote from the movie “The Imitation Game“. The second parameter instead represents the time in milliseconds. Then the function, when called, will start after 2 seconds.

The second function, on the other hand, is a function that contains another alert with another quote, different from the previous one and which has no time limit.

Here, then, is the complete code for using the setTimeout method in JavaScript:



quote();
otherQuote();

function quote() {
  // start after 2 seconds
  setTimeout (function () {
    alert('They are the people that no one imagines that they can do certain things those who do things that no one can imagine!');
  }, 2000);
}

function otherQuote() {
  alert('People never say what they mean, they always say something else. Yet they expect you to understand them ...');
}

Even if the quote function is called first, the otherCitation function will start first as it has no time restrictions.

setTimeout JavaScript and clearTimeout

Let’s create a simple count that we will stop with the clearTimeout method.

Then, let’s prepare our HTML page with this simple code:

  <div id="container">Inizio conteggio:
    <span id="conta"></span>
    <button id="stop" class="btn">stop</button>
  </div>

So I use a span where I’m going to put the progressive numbers and a button to stop everything.

Then I program my algorithm in JavaScript.

We initialize the count variable to 0 and save the timer created in a variable named myTimer.

Inside the callback function we will increment the count variable and then recursively call the setTimeout method to produce the next increments. Let’s give the time of 1 second.

When we click the stop button we call the stopCount function which will call the clearTimeout method on the myTimer variable.

Here is the complete code that uses the JavaScript setTimeout and clearTimeout methods:



var count = 0;
var myTimer = setTimeout(function timer() {
  document.getElementById("count").innerHTML = ++count;
  myTimer = setTimeout(timer, 1000);
}, 1000);

var stop = document.getElementById('stop');
    stop.addEventListener('click',function (){
    stopCount();
});

function stopCount() {
    clearTimeout(myTimer );
}

Conclusion

In this lesson we speak about setTimeout and clearTimeout in JavaScript, in the next lesson we will talk about timers again using the setInterval method.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

functions in JavaScript

functions in JavaScript

In this lesson we will delve into the functions in JavaScript, already introduced in the previous lesson. The lesson can be consulted at the following link: introduction to functions.

functions in JavaScript – examples

In particular, in this example I propose a demonstration of how it is possible to use multiple returns. So let’s create a function named isPositivo and return a value depending on the result of our conditional statement contained within the function.

We therefore pass a number a as a parameter. After, if the number is positive, the function returns 1, if it is null it returns 0, otherwise if it is negative it returns -1.

This is an example of functions in JavaScript:



function isPositive (a) {
  if (a> 0) {
    return 1;
  }
  else if (a == 0) {
    return 0;
  }
  else {
    return -1
  }
}

So we call the function, passing as a parameter, for example, the number -6. We store the return value in a variable named result. Finally we print the result obtained in the console.log().



var result = isPositive(-6);
console.log(result);

In this case we display the value -1 in our console.

Of course, you can return any value, even a string.

So, this is another example of using functions in JavaScript:



function isPositive(a){
  if (a > 0){
    return 'Positive';
  }
  else if (a == 0){
    return 'Null';
  }
  else {
    return 'Negative';
  }
}

var result = isPositive(-6);
console.log(result);

The same function could be written using a variable that for example I set to an initial value. Then only if certain conditions occur I change the value.

Here is a possible change to the previous function, using a string:



function isPositive(a){
  var result = 'Negative';
  if (a > 0){
    result = 'Positive';
  }
  else if (a == 0){
    result = 'Null';
  }
 return result ;
}

var result = isPositive(-6);
console.log(result);

So I change the value of the variable only if the number is positive or null.

Note that the variable result contained within the function is not visible externally. In fact it is a local variable of the isPositivo function. So I can use the same name to store the return value from the function.

Conclusion

In this lesson we have developed a simple example of a function with the possibility of handling different returns, in the next lessons we will talk more about functions in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts