Detecting Online/Offline Status in Javascript

Learn how to detect if the user is online or offline and handle events if a change in the online/offline stateĀ occurs.

We can detect if the user is online or offline by using the online property on the navigator object which will return true if the user is connected to the internet, otherwise it returns false.

Additionally, online and offline events will be triggered if the user’s internet connections state changes. So we can add an online and offline event listener to the window and perform respective actions based on the online and offline state.

online offline State handler in Javascript

The above codepen was originally created by Pulkit Aggarwal. Thanks šŸ™ 😊 to Pulkit Aggarwal.

Thanks for Reading šŸ“–. I hope you liked this mini lesson. If you found any typos or mistakes, send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Different ways to Iterate through Map in Java

Learn different ways to iterate through Map object in Java.

Image fromĀ unsplash

Let’s create a Map

Map<String , String> fruits  = new HashMap<>();
fruits.put("apple" , "šŸ" );
fruits.put("banana" , "šŸŒ" );
fruits.put("grapes", " šŸ‡ ");

Method 1Ā : Java 8 forEachĀ method

fruits.forEach( 
    (k, v) -> System.out.println("Key : " + k + " value : " + v) 
  );

Method 2: Looping by getting Entries of MapĀ .

Set< Map.Entry<String, String> > entries = fruits.entrySet();
for(Map.Entry<String,String> entry : entries) {
   String key = entry.getKey();
String value = entry.getValue();
   System.out.println(key + " <--> " + value);
}

NoteĀ : If we use for-each loop don’t forgot to check if the Map is not nullĀ ,otherwise it will throw NullPointerExceptionĀ .

Method 3: Using Keys of Map in forEachĀ loop

To get keys of the Map

Set<String> keys = fruits.keySet();
for(String key : keys) {

String value = fruits.get(key);

System.out.println(key + " <--> " + value);
}

Method 4: Using Iterator on entries ofĀ Map.

We can create iterator for entrySet of the mapĀ ,then use that to loop through each entry of the map.

Set<Map.Entry<String, String>> entries = fruits.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()){
   Map.Entry<String, String> entry = iterator.next();
   String key = entry.getKey();
   String value = entry.getValue();
   System.out.println(key + " <--> " + value);
}

If you only want keys you can get Keys by

Set<String> keys =fruits.keySet();

If you only want values of the map

Collection<String> values =  fruits.values();

Thanks for Reading šŸ“–Ā . Hope you like this. If you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Other Java Articles You May Like to Explore
The 2019 Java Developer RoadMap
10 Things Java and Web Developer Should Learn in 2019
10 Testing Tools Java Developers Should Know
5 Frameworks Java Developers Should Learn in 2019
5 Courses to Learn Big Data and Apache Spark in Java
10 Courses to learn DevOps for Java Developers
10 Books Every Java Programmer Should Read
10 Tools Java Developers uses in their day-to-day work
10 Tips to become a better Java Developer

View at Medium.com

Creating Dice in Flexbox in CSS

Learn how to create dice in CSS usingĀ flexbox

Dice created with flexbox inĀ CSS

First Face

First face of theĀ div

Our first-face of the die will have one dot at the center.

<div class="dice first-face">
<span class="dot"> </span>
</div>

Here, we have the dice– and dot-classed elements. Now we can add some CSS to the die.

.dice {  
padding: 4px;
background-color: tomato;
width: 104px;
height: 104px;
border-radius: 10%;
}

Now, it creates a box like this.


Now, let’s add some style to the dot.

.dot {
display: block;
width: 24px;
height: 24px;
border-radius: 50%;
background-color:white;
}

This will add a circle inside the dice div. Now, the dice container looks like:


Now, let’s make the dot container appear on the center of the dice container. For that, we need to make the first-face as flexbox and apply:

justify-content:center → will make the dot align to the center of the main axis (horizontal).

align-items:center → will make the dot align to the center of the cross axis (vertical).

.first-face {
display: flex;
justify-content: center;
align-items: center;
}

Second Face

Second face of theĀ die

Now, we need create a die with two dotsā€Šā€”ā€Šone dot at the top-left corner and another at the bottom-right corner.

<div class="dice second-face">
<span class="dot"> </span>
<span class="dot"> </span>
</div>

Make the second face as flex, and add:

justify-content: space-between → This will place the children at the beginning and the end of the flex-container.

.second-face{
display: flex;

justify-content : space-between;
}

The above code will create a dice like this:


The first dot is in the correct place: the top-left corner. Now, we need to align the second dot to the bottom-right corner. For that, apply the align-self property to the second dot of the die.

align-self: flex-end → will align the item to the end of the flex container.

.second-face .dot:nth-of-type(2) {
align-self: flex-end;
}

Third Face


For achieving the third face, we’ll have three dots: one at the top left, one at the center, and one at the bottom right of the die.

<div class="dice third-face">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>

We can achieve the third-face by placing an another dot center to the second-face.

justify-content: space-between → This will place the children at the beginning and the end of the flex-container.

.second-face{
display: flex;

justify-content : space-between;
}

Now, we need to make the last dot (third dot) that’ll be placed in the bottom-right.

.second-face .dot:nth-of-type(3) {
align-self: flex-end;
}

Align the middle dot (second dot) at the center of the parent.

.second-face .dot:nth-of-type(2) {
align-self: center;
}

If we want the first dot in the top-right and the last dot in the bottom-left, then change the first dot’s align-self to flex-endā€Šā€”ā€Šautomatically the third dot will be placed to the bottom-left because the default property of align-self is flex-start.

Third faceĀ altered
.third-face .dot:nth-of-type(1) {
align-self :flex-end;
}
.third-face .dot:nth-of-type(2) {
align-self :center;
}

Fourth Face


In our fourth face, we can split it in two rows, each row containing two columns. One row will be at flex-start, and another will be at flex-endĀ .

<div class="fourth-face dice">
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>

The above code will create a die like this:


Now apply display: flex.

.fourth-face {
display: flex;
}


Add the justify-content property space-between so it’ll be placed at the left and right of the die.


Now, we need to make the dots in the column elements at top and bottom. For that:

  • Set column to flex
  • Apply flex-direction as column so the dots are placed in the column axis
  • Add justify-content as space-betweenā€Šā€”ā€Šit’ll make the first dot at top and second dot at bottom.
.fourth-face .column {
display: flex;
flex-direction: column;
justify-content: space-between;
}

Sixth Face

Sixth face

From the fourth face, we can achieve the sixth face by adding a one-dot div to each column.

<div class="fourth-face dice">
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<div class="column">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>

Fifth Face

Fifth face

We can again create fifth-face from the fourth face by adding another column with one dot and placing the dot (justify-content) at the center.

<div class="fifth-face dice">

<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>

<div class="column">
<span class="dot"></span>
</div>


<div class="column">
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>

Apply all of the properties applied toĀ .fourth-face andĀ .fourth-faceĀ .column toĀ .fifth-face andĀ .fifth-faceĀ .column. That’ll create a die like this:


Now, we need to align the second dot to the center in a vertical direction. For that, we can apply justify-content as center to the column.

.fifth-face .column:nth-of-type(2) {
justify-content: center;
}

That’ll make the die look like a five-face die.


Thanks for reading. Hope you like this.

Find the difference between Dates in JavaScript

Learn how to find difference between two dates in JavaScript.

Image from LukasĀ Blazek

We learn about finding Number of SecondsĀ , Number of MinutesĀ , Number of hoursĀ , Number of daysĀ , Number of weeksĀ , Number of monthsĀ , Number of years between two dates.

Let’s create two dates

let d1 = Date.now();
let d2 = new Date(2019,5,22).getTime(); //Jun 22 2019 in millisecond
console.log(d1); //1573527098946
console.log(d2); //1561141800000

Number of Seconds between twoĀ dates.

1 second = 1000 milliseconds 

Now we are having two date d1 and d2 in milliseconds. To convert milliseconds into secondsĀ ,we can divide the difference between two dates in milliseconds by 1000Ā .

function secondsDiff(d1, d2) {
   let millisecondDiff = d2 - d1;
   let secDiff = Math.floor( ( d2 - d1) / 1000 );
   return secDiff;
}

Number of Minutes between twoĀ dates.

1 minutes = 60 seconds

Now we have method to find the number of seconds between two datesĀ , so we can find seconds difference, then divide that by 60 will give us the number of minutes between two dates.

function minutesDiff(d1, d2) {
     let seconds = secondsDiff(d1, d2);
     let minutesDiff = Math.floor( seconds / 60 );
     return minutesDiff;
}

Number of Hours between twoĀ dates.

1 hour = 60 minutes

Now we have method to find the number of minutes between two datesĀ , so we can find minutes difference, then divide that by 60 will give us the number of hours between two datesĀ .

function hoursDiff(d1, d2) {
   let minutes = minutesDiff(d1, d2);
   let hoursDiff = Math.floor( minutes / 60 );
   return hoursDiff;
}

Number of Days between twoĀ dates.

1 day = 24 hours 

Now we have method to find the number of hours between two datesĀ , so we can find difference, then divide that by 24 will give us the number of days between two dates.

function daysDiff(d1, d2) {
   let hours = hoursDiff(d1, d2);
   let daysDiff = Math.floor( hours / 24 );
   return daysDiff;
}

Number of Weeks between twoĀ dates.

1 week = 7 days

Now we have method to find the number of days between two datesĀ , so we can find difference, then divide that by 7 will give us the number of weeks between two dates.

function weeksDiff(d1, d2) {
   let days = daysDiff(d1, d2);
   let weeksDiff = Math.floor( days/ 7 );
   return weeksDiff;
}

Number of Years between twoĀ dates.

To find number of years between two dates we have in-built method getFullYearĀ , Subtract the date2 year with date1 year, we will get yearsDiffĀ .

function yearsDiff(d1, d2) {
    let date1 = new Date(d1);
    let date2 = new Date(d2);
    let yearsDiff =  date2.getFullYear() - date1.getFullYear();
    return yearsDiff;
}

Number of Months between twoĀ dates.

1 month != 30 days 
Number of days in month is not same in all months , so we need to do it differently

StepsĀ :

  • First we need to find number of years between two dates.
  • Multiply number of years between two dates by 12(because for each year 12 months)
  • Subtract the month number(June → 5) of second date with the month number of first date

Finding number of months between two dates

function monthsDiff(d1, d2) {
  let date1 = new Date(d1);
  let date2 = new Date(d2);
  let years = yearsDiff(d1, d2);
  let months =(years * 12) + (date2.getMonth() - date1.getMonth()) ;
  return months;
}

Thanks for Reading šŸ“–Ā . Hope you like this. If you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Implementing Linear Search in Javascript

Learn how the Linear search Algorithm works and how to implement itĀ .

Linear search is a Searching algorithm, which is used to check if an element is present in an array or listĀ . It is also called Sequential search.

A linear search sequentially search for the target element in the array. If it finds the element in the array it stop searching and returns successfulĀ . If it reaches the end of the array, then it returns element not found.

Algorithm

  1. Traverse the array using a for loop (any looping technique).
  2. In every iteration, compare the target value with the current value of the array.
  • If the values match, return the current index of the array.
  • If the values do not match, move on to the next array element.

3. If no match is found, return element not found.

Link toĀ code

Code can be found here.

Thanks for Reading šŸ“–Ā . Hope you like this. If you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Understanding Switch Statements in JavaScript

Image from negativeĀ space

Whenever we are in situation of writing multiple if/else statement for a particular test case, then the multiple if/else statement can be replaced by switch statement.

SyntaxĀ :

switch(expression_or_value) {

case expression_or_value :
operation1
[break];
   case expression_or_value :
operation2
[break];
    ...  
   default : 
default operation
[break];

}
// break is optional

A switch statement first evaluates its input expression.

It then checks whether the first case expression evaluates to the same value as the result of the input expression, using strict equals (===).

If the case is matched then, the code associated with the case is executed until it finds the break keyword, or also the return keyword inside functions.

If the break or return is not added to the case, then the switch statement will continue and execute the code below the match. It will continue to run until it finds a break, return, or reaches the end of the statement.

If no matching case is found then the program looks for a default clause and executes the code there.

If a default clause is not found, then it reaches end of the switch expression and does nothing.

Example:

function getCost(item) {
  let cost ;
  switch(item) {
    case 'šŸŒ':
cost = '10$';
break;

case 'šŸ‰' :
cost = '20$';

case 'šŸ“' :
cost = '30$';
break;

default :
cost = "Item not in stock";
  }
  return cost;
}

Let’s execute the function and test it

getCost('šŸŒ'); // 10$
getCost('šŸ‰'); // 30$
getCost('apple'); // Item not in stock

getCost(ā€˜šŸŒā€™)→ matches the first case and executes the cost = 10$ and executes the break statement, which ends the switch statement.

getCost(ā€˜šŸ‰ā€™) → matches the second case and executes the cost = 20$. There is no break, so the code below it is executed, and the value of cost starts at 20$ but continues to run and becomes 30$Ā .

getCost(ā€˜apple’) → no matching case, so it executes the default case. For the last case, there is no need for the break statement because there will be no more case below itĀ .

Cases where we can skip break statement

If we want to execute same operation for two or more conditions, then we can make use of skipping break statement.

function isVowel(input) {
  let isVowel = false; 
  switch(input) {
    case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
isVowel = true;
  }
  return isVowel;
}

The order in which the cases are placed is not considered.

We can also place the default case anywhere inside the statement.

function getCost(item) {
  let cost = `The cost of ${item} is `;
  switch(item) {
    default :
cost = "Item not in stock";
break;
    case 'šŸŒ';
cost = '10$';
break;

case 'šŸ‰' :
cost = '20$':

case 'šŸ“' :
cost = '30$';
break;
  }
return cost;
}

But don’t forget to add a break statement to the end of default case if it is not placed at the end of all cases.

We can also add block to eachĀ case

function getMenu(option) {
    switch(option) {

case 'veg' : {
console.log('šŸŽ','šŸ‰','šŸŒ','šŸ“', 'šŸ');
break;
}

case 'non-veg': {
console.log('šŸ—', 'šŸœ', '🄩','šŸ£');
break;
}

default :
console.log('šŸ•','šŸ„“','šŸ„•','šŸ§');

}
  }

But when we need to use that?

In a switch expression, variables created inside any one of the case blocks is available to entire switch block.

function getMenu(option) {
    switch(option) {

case 'veg' :
let menu = ['šŸŽ','šŸ‰','šŸŒ','šŸ“', 'šŸ'];
console.log(...menu);
break;

case 'non-veg':
let menu = ['šŸ—', '🄩','šŸ£']; // this will throw error
console.log(...menu);
break;

default :
console.log('šŸ•','šŸ„“','šŸ„•','šŸ§');

}
  }

The above example throwsĀ , ā€œUncaught SyntaxError: Identifier ā€˜message’ has already been declaredā€, which you were not probably expecting.

To solve this we can use a block {} for the case section.

function getMenu(option) {
    switch(option) {

case 'veg' : {
let menu = ['šŸŽ','šŸ‰','šŸŒ','šŸ“', 'šŸ'];
console.log(...menu);
break;
}
      case 'non-veg': {
let menu = ['šŸ—', '🄩','šŸ£'];
console.log(...menu);
break;
}
      default : 
console.log('šŸ•','šŸ„“','šŸ„•','šŸ§');
    }
}

We can have an expression for the switch andĀ case

switch(1+2) {

case 1:
console.log(1);
break;

case 1+2 :
console.log(3); // this will be executed
break;

}

The switch compares cases with strict equality

switch(1) {

case '1':
console.log(1);
break;

default :
console.log("Default"); // this will be executed

}

Thanks for Reading šŸ“–Ā . Hope you like this if you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Insert an element in specific index in JavaScript Array.

Learn how to insert an element in specific index inĀ array.

Image from unsplash (Zdennek)

We have some in-built methods to add at elements at the beginning and end of the array.

push(value) → Add an element to the end of the array.

unshift(value) → Add an element to the beginning of an array.

To add an element to the specific index there is no method available in Array object. But we can use already available splice method in Array object to achieve this.

An array starts from index 0Ā ,So if we want to add an element as first element of the arrayĀ , then the index of the element is 0Ā .If we want to add an element to nth positionĀ , then the index is (n-1) th index.

MDN : 
   The splice() method changes the contents of an array by removing      or replacing existing elements and/or adding new elements, in the original array(which means the source array is modified)

splice() method takes three argument

  1. start → The index at which to start changing the array.
  2. deleteCount(optional) → An integer indicating the number of elements in the array to remove from start.
  3. (elem1, elem2 …) → The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.

In order to insert an element to the specific indexĀ , we need to provide arguments as

  1. start → index where to insert the element
  2. deleteCount → 0 (because we don’t need to delete element)
  3. elem → elements to insert

Let’s Write the function


function insertAt(array, index, ...elementsArray) {
    array.splice(index, 0, ...elements);
}

Now Let’s call the function

var num = [1,2,3,6,7,8];
/*
arguments
* 1. source array - num
* 2. index to insert - 3
* 3. remaining are elements to insert
*/
insertAt(num, 3, 4, 5); // [1,2,3,4,5,6,7,8]
________________________________________________________________
// let's try changing the index
var num = [1,2,3,6,7,8];
insertAt(numbers, 2, 4,5); // [1,2,4,5,3,6,7,8]

Thanks for Reading šŸ“–Ā . Hope you like this if you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Master Destructing Values in JavaScript

Learn how to destructure array and object properties into variables in JavaScript.

Image fromĀ Unsplash

The destructing syntax allows us to extract multiple values based on the property name from objects or arrays.

                       // Destructing array
var num = [1,2,3,4,5];
var [a, b] = num;
console.log(a, b); //1,2
                       // Destructing Object 

var obj = {
  name : "JavaScript Jeep",
  work : "Blogging"
};

var {name, work} = obj;
console.log(name, work); // "Javascript Jeep", "Blogging"

Array Destructing

Values in arrays are desctructured based on their index. The variable can be named anything you want. The variable name associated with the index is how it is assigned.

var fruits = ["šŸŽ", "šŸŒ", "šŸ"];
var [apple, banana, pineapple] = fruits;
console.log(apple, banana, pineapple); // "šŸŽ", "šŸŒ", "šŸ"

We can also assign value to already declared variables.

var apple = "apple";
var banana = "banana";

[apple, banana] = ["šŸŽ", "šŸŒ"]
console.log(apple, banana); // "šŸŽ", "šŸŒ"

If there are more variables than the length of array, then the value of remaining variables becomes undefined.

var arr = [1]  
var [a, b] = arr;  
console.log(a, b); 1, undefined

Using the rest operator in destructing:

var numbers = [1,2,3,4,5,6];  
var [a, b, ...rest] = numbers;  
console.log(a, b, rest);  // 1, 2, [3,4,5,6]

The restĀ ... operator allows you to accumulate the remaining items that aren’t destructured.

When using rest operator, the rest element should be last element, otherwise it will throw Syntax Error.

var [a, ...b, c] = [1, 2, 3]; // error

var [a, ...b,] = [1, 2, 3]; // error because trailing comma after rest element

Setting Default values to the variables:

var fruits = ["šŸŽ", "šŸ"];

//without default value
var [apple, pineapple, banana ] = fruits;
console.log(apple, pineapple, banana); // "šŸŽ", "šŸ", undefined 
                      // with default value
var [apple, pineapple, banana= "šŸŒ" ] = fruits;
console.log(apple, pineapple, banana); // "šŸŽ", "šŸ",  "šŸŒ"

Skipping values of the array

var num = [1,2,3];
var [one,,three] = num;
console.log(one, three); 1, 3

Tips: With array destructing we can easily swap values

var a = 10,b = 20;

[b, a] = [a, b]

console.log(a, b); 20, 10

Object Destructing

We can extract data from properties of the object using object destructing. Here the name of the variable is matched with the property of the object and the corresponding property value is retrieved from the object and assigned to the variable.

var user = {name : "Ram", age : 20};

var {name, age} = user;
console.log(name, age); // "Ram", 20

Example 2:

var {name, age} = {name: "Ram", age : 20};
console.log(name, age); // "Ram", 20

If the variable name doesn’t match the property of the object, then the value of unmatched variable will be undefined.

var {name, age, salary} = {name: "Ram", age : 20};
salary; //undefined

Using the rest operator

var user = {name: "Mike", age : 30, weight : 50};  
var {name, ...details} = user;  
console.log(name, details);  // "Mike" , {age: 30, weight : 30}

Destructing an already declared variable

var name , age; 
var user = {name: "Ram", age : 20}; 

We can’t do like {name, age} = user; because “{” is the first tokenĀ , so JavaScript thinks it is a start of blockĀ .

To solve this

({name, age} = user);

Assigning to new variable names

var user = {name : "Ram"};
var {name: userName} = user;

userName; // "Ram"

The above code takes name property from user and create a new variable with name userName and assign the value to userName variable.

Tip: We can use new variable name when the property of the object is invalid identifier name

var user = {"user-name" : "Mike"};  
var {"user-name": userName} = user;
userName; //Mike

Assigning Default value

The default value can be assigned to a variable if the property is not present in the object.

var user1 = {name : "Mike", nickName : "mic"};  
var {name1, nickName1="Noob Master"} = user1;  
console.log(nickName1); // "mic"

               //If the property not present 
var user2 = {name : "Ram"};  
var {name2, nickName2="Noob Master"} = user2;  
console.log(nickName2); //"Noob Master"

Using both default values and new variable names

var user = {};  
var { name: userName = "Default Name" } = user;  
console.log(userName); // "Default Name"

Using Object Destructing as function arguments

Without destructing

function logUser(user) 
{
var name = user.name;
var age = user.age;
console.log(name, age);
}
var user = {name : "Mike", age : 20}; 
logUser(user); // "Mike", 20

The above code can be simplified to

function logUser( {name, age} ) 
{
console.log(name, age);
}
var user = {name : "Mike", age : 20}; 
logUser(user); // "Mike", 20

Using default value and new variable name in function argument destructing

function logUser( {name:userName, age: userAge = 30} ) 
{
    console.log(userName, userAge); 
}  
var user = {name : "Mike"}; 
logUser(user); // "Mike" , 30

The above method logUser will throw an error if we call the method without any argument. If we don’t pass any argument, it tries to destructure undefined so it throws error. To resolve this:

function logUser({name: Name="Jack", age: Age = 30} = {}) 
{

console.log(Name, Age);
} 
logUser(); // Jack 30

Thanks 😊 šŸ™ for Reading šŸ“–.

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Essential DOM Operations with JavaScript

Learn about some basic but essential DOM methods in JavaScript

Image by Pankaj Patel fromĀ Unsplash

The below code is what we’ll use to access and manipulate with our JavaScript DOM methods:

<div id="parent"> 
<div class="child one"> < /div>
<div class="child children second"> < /div>
<div class="child third"> < /div>
</div>
  1. Select and element by id. It will always return 1 element since id’s are required to be unique.
document.getElementById(element_id);
Example:
document.getElementById('parent'); 

2. Select all elements by class name.

document.getElementsByClassName(class_name); 
// return all elements with class name as an array
Example: 
document.getElementsByClassName('child'); // return child element
document.getElementsByClassName('child children');
// the above returns element which has both child & children class

3. Select and element by tag name

document.getElementsByTagName(tag_name);
Example: 
document.getElementsByTagName('div');

4. Select the first element by selector, which returns the first element within the document that matches the specified group of selectors.

document.querySelector(selector);
Example
document.querySelector('.child'); 

5. Select all elements by selector.

document.querySelectorAll(selector);
Example 
document.querySelectorAll('.child');

6. Get child elements of an element.

var parent = document.getElementById('parent');
parent.childNodes; returns NodeList
parent.children; returns HTMLCollection

7. Find the number of children.

var parent = document.getElementById('parent');
parent.childElementCount; // 2

8. Find the parent node.

var child = document.querySelector('.child');
child.parentElement;

9. Creating a new DOM element.

var div = document.createElement('div');

10. Creating a text element.

var h1 = document.createTextNode("This is text element");

11. Add an element as a child node as the last sibling of its adjacent nodes.

var parent = document.getElementById('parent');
var div = document.createElement('div');
parent.append(div);

12. Add an element as a child node as the first sibling of its adjacent nodes.

var parent = document.getElementById('parent');
var div = document.createElement('div');
parent.prepend(div);

Thanks 😊 šŸ™ for Reading šŸ“–.

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

An Overview of Array Methods in JavaScript

Learn about how to manipulate arrays in JavaScript

Image by Paweł Czerwiński fromĀ Unsplash

Let’s create an array:

var numbers = [1,2,3,4,5]

Array elements are accessed using an index. The index starts from 0Ā . So if we want to access the first element, then we need to access using index 0.

numbers[0] // 1
numbers[3] // 4
numbers[9] // undefined

Find the length of theĀ array

numbers.length

Get the last element of theĀ array

let len = numbers.length;
let index = len - 1;
let lastElement = numbers[index]

Adding an element to the end of anĀ array

numbers.push(6);
numbers; // [1,2,3,4,5,6]

Adding element to the beginning of anĀ array

numbers.unshift(0);
numbers; // [0,1,2,3,4,5,6]

Deleting the last element of anĀ array

numbers.pop()

Delete the first element of theĀ array

numbers.shift()

Delete an element at specificĀ index

let numbers = [1,2,3,4,5];
let index = 2;
numbers.splice(index,1);
numbers; [1,2,4,5]

Adding an element at a specificĀ index

let numbers = [1,2,5];
let index = 2;
let elements = [3,4]
numbers.splice(index,0, ...elements);
numbers; [1, 2, 3, 4, 5]

Updating elements

var numbers = [1,2,2,4,5]
numbers[2] = 3;
numbers; // [1,2,3,4,5]

Find if an element is present in anĀ array

var numbers = [1,2,3,4,5]
numbers.includes(1);// true
numbers.includes(10);// false

Find the index of theĀ element

var numbers = [1,2,3,4,5]
numbers.indexOf(1); // 0
numbers.indexOf(10); // -1(if element not present )

Iterating over anĀ array

var numbers = [1,2,3,4,5]
for(let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// example 1
numbers.forEach(elem => console.log(elem));

Reverse anĀ array

var numbers = [1,2,3,4,5]
numbers.reverse(); // [5, 4, 3, 2, 1]

Filter arrayĀ elements

var numbers = [1,2,3,4,5];
numbers.filter((elem) => elem > 3);// [4,5]

Mapping all elements with function and create a newĀ array

var numbers = [1,2,3,4,5]; 
var doubledNum =  numbers.map(item => item *2 );
doubledNum; // [2,4,6,8,10]

Sorting anĀ array

let num= [1, 2, 3, 4, 5, 6];
// sort in descending order
let descOrder = num.sort( (a, b) => a > b ? -1 : 1 );
console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]

// sort in ascending order
let ascOrder = num.sort((a, b) => a > b ? 1 : -1);
console.log(ascOrder); // output: [1,2,3,4,5,6]

Create a string fromĀ Array

var test = ["This", "is", "a", "test."]
test.join(" "); // "This is a test."

Thanks 😊 šŸ™ for Reading šŸ“–.

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Please make a donation here. 80% of your donation is donated to someone needs food 🄘. Thanks in advance.

Design a site like this with WordPress.com
Get started