Css selector for element which have numbers as class name.

Learn how to select the element which has the class name starting with number.


HTML5 supports numbers as id and class nameĀ , but css selector have some rulesĀ ,

  • A valid name should start with a letter (a-z)[A-Z]Ā , an underscore (_), or a hyphen (-) which is followed by any numbers, hyphens, underscores, letters.
  • A name should be at least two characters long.
  • Cannot start with a digit, two hyphens or a hyphen followed by a numberĀ .

If you are using numbers as class or id name

<h1 class = "10"> 10 class name </h1> 

Then, you need to escape it based on its Unicode code point. To escape itĀ , the code point for the character 1 is U+0031, so you would escape it as 00031 or 31Ā .

Simply to escape any numeric character, just prefix it with 3 and append a space characterĀ .

Now we need to write css as
.31 0 {
  color :red;
}

To escape special character we can use

<h1 class = "#"> Special chanracter </h1>
.# {
color :blue;
}

To find unicode code-point use this function

function getUnicodeCodePoint(char) {
   var hex = "1".codePointAt(0).toString(16); 
   return "\u" + "0000".substring(0, 4 - hex.length) + hex;
}

If you don’t understand or don’t want to add difficulties to your codeĀ , then you can use this simple method.

<h3 class="10"> simple selector </h3>
[class = '10'] {
  color : brown;
}

References

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Remove All children šŸ‘¶ of the node in Javascript.

Learn how to delete all the nodes inside a div or any node in Javascript.


You can do it in three ways

1Ā . Set the node innerHTML as empty-string(ā€œā€).

var node = document.getElementById('parent');
node.innerHTML = "";

This method removes all the text and nodes inside the parent node. If you need to delete only the nodes then you can go for second method.

2. Second way is to remove firstChild of the parent node until the node has a childrenĀ ,

var node= document.getElementById("parent");
while (node.firstChild) {
    node.removeChild(myNode.firstChild);
}

3. You can also use node.remove() method to delete the nodes

var node= document.getElementById("parent");
node.querySelectorAll('*').forEach(n => n.remove());

If you’re using jQuery then we can empty the parent by $(node).empty()

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Understanding weirdness of the ā€œ!ā€ bang operator in JavaScript

There are some things we don’t know about how theĀ ! operator works in Javascript.


Basics

TheĀ ! is a logical operator that will convert a value to its opposite boolean. Since JavaScript will coerce values, it will ā€œconvertā€ a value to its truthy/falsey form and return the opposite boolean value.

When we perform theĀ ! operation on a number other than 0 it, returns false. This is because all numbers other than 0 are truthy.

// evaluates to false
!1
!-10
!1.2

TheĀ ! operation on 0, null, undefined, NaN returns true since they are falsey.

//evaluates to true
!0
!NaN
!null
!undefined

If we performĀ ! on undefined variables then it returns true.

var a ;
!a // true

Similarly, if we performĀ ! on a variable which has some value or points to some a reference then it returns false.

var a = [];
!a; // false

The weirdĀ part

When we do:

! + [] // then it is evaluated to true 

The reason is, the + operator only works on strings and numbers, so if we perform a binary operation on an array, then the array is converted to a string. So the detailed view is:

! + [] 
is converted internally into
! + String([])
! + "" //it evaluates true because ! on empty string returns true

So now let’s try another large problem (which I found on Twitter, the solution also available there 😃)

(! + [] + [] + [] + ![]) 
! + [] --> true 
true + [] --> "true"
"true" +[] --> "true"
"true" + ![] -- >"truefalse"

If you want to learn more about these concepts, you should study JavaScript type coercion and how truthy/falsey values work in JS.


If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.


https://gitconnected.com/learn/javascript

Getting max of numbers in Javascript.

Learn how to get the maximum of numbers.


max function in the Math object can be used to find the maximum of multiple numbers and array.

Math.max(1,2); //2
Math.max(1,2,3); //3

If any one of the argument passed cannot be converted to number then it returns NaN

Math.max('1', 0); //1
Math.max('one', 1); // NaN
Math.max(1, 2, 3, 4, 5, 'one', 1); // NaN

We can use Math.max to find the maximum of the array

var array = [1,2,3,4,5];
Math.max(...array);

If you have array inside array you need to flatten the array then apply the max function.

To flatten an array without knowing the depth you can refer here

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Flatten an array in javascript

Learn how to convert a multi-dimensional array into single dimension array in javascript

Flattening the array in Javascrip

We can flatten an array to single dimension array using Array.flat(depth) method.

But if we have multi-dimensional array then we need to find the depth of the Array, instead of finding depth we can solve the problem in two ways

we can pass Infinity as depthĀ ,


InputĀ : [1,2,3, [2,3,[1,2,[3,4]],4,5,6]];

Expected OutputĀ : [1,2,3,2,3,1,2,3,4,4,5,6]

Consider we have input and result arrayĀ .

We can loop through each element in input array,

If

  • current element is not an array then push the element into the result array,
  • current element is an array then again loop through all the elements of the current elementĀ , if we have another array then call the same function recursivelyĀ .


There is another simple way to do the same using the string split method,
var a = [1,2,3, [1,2, [1,2, [1,2] ] ] ];
a = a + ""; // results in --> 1,2,3,1,2,1,2,1,2
a = a.split(',');  // ["1", "2", "3", "1", "2", "1", "2", "1", "2"]

But all the elements are converted to stringĀ , if it is not a problem then we can use this method.

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Removing space in string in Javascript

Learn how to remove space in string.

If you want to remove all the space in the string thenĀ , you can use replace method

var name = "Javascript jeep  ";
name.replace(/s/g,''); // Javascriptjeep
s --> space
g --> replace globally
We can also replace the space with '-'
var name = "Javascript jeep  ";
name.replace(/s/g,'-'); // Javascript-jeep--

If you want to remove the extra space at the end of the string then you can use

var s = "string   ";
s = s.trimRight();    //string
//trimRight() returns a new string, removing the space on end of the string

If you want to remove the extra space at the beginning of the string then you can use

var s = "    string";
s = s.trimLeft();    //string
//trimLeft() returns a new string, removing the space on start of the string

If you want to remove the extra space at the both end of the string then you can use

var s = "   string   ";
s = s.trim();    //string
//trim() returns a new string, removing the space on start and end of the string

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Misunderstanding on parsing Boolean

Learn about how to parse boolean in Javascript.


Creating a boolean value using Boolean constructor

var b = new Boolean();

b is an object which have the value false in it. But the problem here is most of the beginner think as we can use directly in ifĀ , but it results to misunderstanding

if(b) {
   console.log("b is an object so it comes inside if");
}

b is no the boolean valueĀ , it is a boolean objectĀ . So we can’t use it directly to check the condition (Do not use a Boolean object in place of a Boolean primitive.). either we can use.

var booleanValue = b.valueOf()

The valueOf method of Boolean returns the primitive value of a Boolean object

Bonus 🤩

var b = Boolean('false');  evaluates to true
We can use 
var b = JSON.parse('false'); evaluates to false

Bonus Again 🤩🤩

Boolean value that are evaluates to false (source from mdn)

var noParam = new Boolean();
var zero = new Boolean(0);
var Null = new Boolean(null);
var EmptyString = new Boolean('');
var falseVal = new Boolean(false); 

Boolean value that are evaluates to true(source from mdn)

var trueVal = new Boolean(true);
var trueString = new Boolean('true');
var falseString = new Boolean('false');
var str = new Boolean('Javascript Jeep šŸš™ šŸš— ');
var ArrayVal = new Boolean([]);
var obj = new Boolean({});

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

How to convert 24 hours format to 12 hours in Javascript.

Convert the 24 hours format time to 12 hours formatted time.


You can get the time byĀ ,

var dt = new Date();
var hours = dt.getHours(); // gives the value in 24 hours format
var minutes = dt.getMinutes() ; 
var finalTime = "Time  - " + hours + ":" + minutes; 
finalTime // final time Time - 22:10

Now in-order to convert it to 12 hours format you can take % 12 on the current time.

If the time is 13 then 13%12 → 1

time = 23 then 23%12 →11

time = 24, then 24%12 → 0Ā , if the time is 0, then change the time as 12.

var dt = new Date();
var hours = dt.getHours() ; // gives the value in 24 hours format
var AmOrPm = hours >= 12 ? 'pm' : 'am';
hours = (hours % 12) || 12;
var minutes = dt.getMinutes() ;
var finalTime = "Time  - " + hours + ":" + minutes + " " + AmOrPm; 
finalTime // final time Time - 22:10

If you find this helpful surprise šŸŽ me here.

Share if you feel happy.

Follow Javascript JeepšŸš™ if you feel worthy.

Creating a simple loader only using CSS

Loader are the impressing part of the websiteĀ , which needs to be simple and funĀ , So we will build an elegant loaderĀ .

This loader is inspired from here.


Create a container which is going to hold the loader

<html>
   <body>
      <div class="container"> 
      </div>
   </body>
</html>

Set the width and height of the body to 100%Ā , also change the display as flex so that we can easily centre the container with respect to screen.

html, body {
  width: 100%;
  height: 100%;
  display: flex;
//to centre container, set justify-content and align-items - centre.
  justify-content: center;
  align-items: center;
  background: #FCEAFC;
} 

Add height and width to the contianer

.container {

width : 320px;
  height : 180px; // we have six colours each 30px;
}

Now we need to create div for each colorĀ ,and place it inside the container.

<div class="color">
    <div class="red"></div>
</div>
<div class="color">
    <div class="orange"></div>
</div>
<div class="color">
    <div class="yellow"></div>
</div>
<div class="color">
    <div class="green"></div>
</div>
<div class="color">
    <div class="blue"></div>
</div>
<div class="color">
    <div class="purple"></div>
</div>

set the height to the loader

.container .color {
  height: 30px;
}
.container .color div {
  height: 30px;
  width: 100%;
}

No we need to add background to each colorĀ ,

red {
background: #f25774;
}
 .orange {
background: #ffb65b;
}
.yellow {
background: #fdda74;
}
.green {
background: #4cbe5d;
}
.blue {
background: #4080ff;
}
.purple {
background: #7b64c0;
}

Now the loader looks like


For animating the color we need to initially set the width to 0 and then when we change the width to 100% this will create an expanding effect.

.container .color div {
  width: 0;
  animation-name: slide;
  animation-duration: 2.5s;
  animation-iteration-count: infinite;
}
@keyframes slide {
10% {
    width: 0;
  }
  37% {
    width: 100%;
  }
  63% {
    width: 100%;
  }
  90% {
    width: 0;
  }
}

Assign the animation to the color divĀ , add 1s delay to each div so that the animation appear one after another

.color
.red {
animation-delay: 0.1s;
}
.orange {
animation-delay: 0.2s;
}
.yellow {
animation-delay: 0.3s;
}
.green {
animation-delay: 0.4s;
}
.blue {
animation-delay: 0.5s;
}
.purple {
animation-delay: 0.6s;
}

Final loader

In order to change the above into end in the right side we can add float property to the div color div

@keyframes slide {
  10% {
    width: 0;
    float: left;
  }
  37% {
    width: 100%;
    float: left;
  }
  63% {
    width: 100%;
    float: right;
  }
  90% {
    width: 0;
    float: right;
  }
}

Now we get the expected loader.

Difference between String primitives and String object.


Learn about, in what way the string primitive and string objects are different in javascript.

We can create string in three ways,

1. var a = "first way"; // we can also use single quotes
2. var b = String("second way");
3. var c = new String("third way");
// also we can create using 
4. var d = a + '';

The 1 and 2 will create primitive stringĀ , where as 3 will create a String object. But we can call all the string methods on the primitive string created from 1 and 2Ā , when we call one of the String object method on primitive String the browser will automatically convert the primitive string into string objectĀ .

Check the type of the strings created using typeof operator

typeof a     // "string"
typeof b     // "string"
typeof c     // "object"

The string primitive is always parsed, i.e(string literal are treated as source code)Ā , where as the string object is evaluated into a single stringĀ .

String primitives and String objects also give different results when using eval().

Primitives passed to eval are treated as source code.

String objects are treated like other objectsĀ , and it returns the object.

var a = "12 + 12";
eval(a); // 24
var b = new String("12 + 12");
eval(a); "12 + 12"

So how we can use String object in evalĀ ?

We can use valueOf() method in String object which will return the string as primitive value

var a = new String("12 + 12");
eval ( a.valueOf() ) // 24

This above concept works same for Numbers and Boolean.

Design a site like this with WordPress.com
Get started