Categories
JavaScript Answers

How to Add CSS Styles with JavaScript?

Sometimes, we want to add CSS styles dynamically into our web page with JavaScript.

In this article, we’ll look at ways to add CSS styles dynamically with JavaScript.

Using the window.document.styleSheets Object and the insertRule Method

We can get the first stylesheet for a document with the window.document.styleSheets property.

Then we can call the insertRule method on the returned stylesheet object.

For instance, if we have the following HTML code:

<strong>hello world</strong>

Then we can make the strong element text display in red by writing:

const [sheet] = window.document.styleSheets;
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

We use the destructuring syntax to get the first stylesheet from the window.document.styleSheets iterable object.

Then we call insertRule on the stylesheet object with our CSS string as the first argument.

Then we should see that the strong element text is red.

Create a style Element

Another way to add CSS styles with JavaScript is to use the document.createElement method to create a style element.

For instance, if we have the following HTML code:

<strong>hello world</strong>

Then we can create the style element by writing:

const styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = 'strong { color: red; }'
document.head.appendChild(styleSheet)

We call document.createElement with 'style' to create a style element.

Then we set the type property on the resulting styleSheet object.

And then we set the innerText property to the CSS styles we want to apply.

Finally, we call document.head.appendChild with styleSheet to append the style element we created into the head element as its child.

Therefore, we should get the same result as before.

Conclusion

We can add CSS styles with JavaScript by creating a style element or getting the first style sheet with JavaScript and add the style rules we want to it.

Categories
JavaScript Answers

How to Access the Resolved Value of a JavaScript Promise?

On many occasions, we want to get the resolved value of a JavaScript promise.

In this article, we’ll look at how to access the resolved value of a JavaScript promise.

Call then with a Callback

One way to get the value resolved value of a JavaScript promise it to call the then method with a callback that has one parameter.

The parameter has the resolved value.

For instance, we can write:

Promise.resolve(1)  
  .then((result) => {  
    console.log(result)  
  });

We call Promise.resolve to return a promise that resolved to 1.

Then we call then on it with a callback that has the result parameter.

result should have the resolved value of the promise.

And so the value of result is 1.

Using the async and await Syntax

We can also get the resolved value of a promise with the async and await syntax.

For instance, we can write:

(async () => {  
  const result = await Promise.resolve(1)  
  console.log(result)  
})()

We assign the resolved value of the promise with the await syntax to the result variable.

Therefore, result should also be 1 in this example.

await can only be used inside an async function.

Conclusion

We can get the resolved value of a JavaScript with the await keyword in an async function or call then with a callback that has the resolved value as the first parameter.

Categories
JavaScript Answers

How to Check if an Object Value Exists within a JavaScript Object Array and if not, Add a New Object into the Array?

Sometimes, we want to check if an object value exists within a JavaScript object array and if not, add a new object into the array.

In this article, we’ll look at how to check if an object value exists in an array and insert a new entry if it doesn’t exist.

Using the Array.prototype.some Method

We can use the some JavaScript method to check if an entry with the given condition exists in a JavaScript array.

And we can use the push method to add a new entry into the array.

To use it to check if an entry with the given condition exists and add an entry if it doesn’t exist, we can write:

const arr = [{
  id: 1,
  username: 'fred'
}, {
  id: 2,
  username: 'bob'
}, {
  id: 3,
  username: 'ted'
}];

const add = (arr, name) => {
  const {
    length
  } = arr;
  const id = length + 1;
  const found = arr.some(el => el.username === name);
  if (!found) {
    arr.push({
      id,
      username: name
    });
  }
  return [...arr];
}

const newArr1 = add(arr, 'ted')
const newArr2 = add(arr, 'james')
console.log(newArr1);
console.log(newArr2);

We have the arr array which we want to check if an entry with the given username exists and add a new entry with the given username if it doesn’t.

To do this, we create the add function that takes the arr array to check and the name to look up.

In the function, we get the length of arr and set the id to length + 1 .

Then we call arr.some with a callback that returns whether the el array entry meets the condition el.username === name and assign the result to found

If found is false , that means an entry with username equal to the name doesn’t exist.

And so we call arr.push with a new entry with the given name as the username .

Then we return a copy of arr to make sure we don’t modify the original arr array.

Therefore, newArr1 is:

[
  {
    "id": 1,
    "username": "fred"
  },
  {
    "id": 2,
    "username": "bob"
  },
  {
    "id": 3,
    "username": "ted"
  }
]

And newArr2 is:

[
  {
    "id": 1,
    "username": "fred"
  },
  {
    "id": 2,
    "username": "bob"
  },
  {
    "id": 3,
    "username": "ted"
  },
  {
    "id": 4,
    "username": "james"
  }
]

Conclusion

We can use the some JavaScript method to check if an entry with the given condition exists in a JavaScript array.

And we can use the push method to add a new entry into the array.

Categories
JavaScript Answers

How to Serialize an Object into a List of URL Query Parameters with JavaScript?

Sometimes, we want to convert the key-value pairs of a JavaScript object into a query string with the key-value pairs in the object as query parameters.

In this article, we’ll look at how to serialize an object into a list of URL query parameters with JavaScript.

Use the URLSearchParams Constructor

We can use the URLSearchParams constructor that’s available with most modern browsers to convert a JavaScript object into a query string.

For instance, we can write:

const obj = {
  param1: 'something',
  param2: 'somethingelse',
  param3: 'another'
}
const url = new URL(`http://example.com`);
url.search = new URLSearchParams(obj);
console.log(url.toString())

to create the obj Object that we want to convert to a query string with the key-value pairs being added to the query string.

We then create the url object with the URL to create the URL instance.

Next, we set the url.search property to the query string we want to set.

To create the query string, we use the URLSearchParams constructor with obj to create the query string object. The query string will be appended to the URL when we convert it to a string.

In the last line, we call toString to convert the URL instance to a URL string.

As a result, the console log should log:

http://example.com/?param1=something&param2=somethingelse&param3=another

Conclusion

We can serialize a JavaScript object into a query string with the URLSearchParams constructor.

Categories
JavaScript Answers

How to Get the Number of Minutes Between Two Dates with JavaScript?

Sometimes, we want to get the number of minutes between 2 dates with JavaScript.

In this article, we’ll look at how to get the number of minutes between 2 dates with JavaScript.

Subtract 2 Dates After Converting the Dates to Timestamps and Convert the Difference to Minutes

We can convert JavaScript date objects to timestamps, subtract them, and then convert the difference to minutes.

To do this, we write:

const d2 = new Date(2020, 2, 1);  
const d1 = new Date(2020, 1, 1);  
const diffMs = +d2 - +d1;  
const diffMins = Math.floor((diffMs / 1000) / 60);  
console.log(diffMins)

We have the d2 and d1 date objects, which we want to get the difference in minutes between.

In the 3rd line, we convert the d2 and d1 date objects to timestamps in milliseconds with the + operator in front of them.

Then we divide diffMs by 1000 to convert the difference in seconds.

And then we divide that by 60 to convert it to minutes.

Then from the console log, we should see the number of minutes difference between d2 and d1 is 41760.

We can also convert d2 and d1 to timestamps with the getTime method.

For instance, we can write:

const d2 = new Date(2020, 2, 1);  
const d1 = new Date(2020, 1, 1);  
const diffMs = d2.getTime() - d1.getTime();  
const diffMins = Math.floor((diffMs / 1000) / 60);  
console.log(diffMins)

And we get the same result as before.

Conclusion

We can get the difference between 2 dates in minutes by converting to timestamps in milliseconds, subtract the 2 timestamps, and convert the difference to minutes.