Categories
JavaScript Answers

How to Change an Element’s Class with JavaScript?

If we’re working with web front end apps, then changing an element’s class is something that we’ve to do often.

In this article, we’ll take a look at how to change an element’s class with JavaScript.

The classList Property

An element has the classList property to let us manipulate the classes that are applied to the element.

For instance, if we have a div:

<div>
  hello world
</div>

Then to add a class to the div, we can write:

document.querySelector("div").classList.add('hello');

We call add to add the 'hello' class to the div.

If the hello class is already added, then nothing will be done.

To remove a class, we can call the classList.remove method:

document.querySelector("div").classList.remove('hello');

To check if a class is already present in an element, we can use the classList.contains method:

document.querySelector("div").classList.contains('hello');

It returns true if the class is applied to the div and false otherwise.

And to toggle class that’s applied to an element, we can call the classList.toggle method:

document.querySelector("div").classList.toggle('hello');

If the hello class is applied to the div, then it’ll be removed.

Otherwise, the hello class will be added to the div.

This is available in most recent browsers.

The className Property

Another way to manipulate classes of an element is to manipulate the className string property.

For instance, we can write:

document.querySelector("div").className = 'hello';

We get the div and set the className to 'hello' to set the class attribute of the div to 'hello' .

To add a class by manipulating the className property, we can write:

document.querySelector("div").className += ' hello';

We add a space and hello to add the hello class to the div.

To remove the hello class, we can use the replace method:

document.querySelector("div").className.replace(/(?:^|s)hello(?!S)/g, '')

We check for hello with possible spaces at the start or end of the class name and replace them with an empty string.

The g flag will find all the instances of this and do the replacement on all of them.

To find if a class is in the div, we can write:

document.querySelector("div").className.match(/(?:^|s)hello(?!S)/)

We call match with the regex that matches hello with whitespace before or after it to check if the class is in the className string.

Conclusion

The best and easiest way to manipulate classes of an HTML element is to use the classList property.

Alternatively, we can also manipulate the className string property to change the class attribute of an element.

Categories
JavaScript Answers

How to Get All Unique Values in a JavaScript Array?

Removing duplicate values from an array is something that we’ve to do sometimes in our JavaScript apps.

In this article, we’ll look at how to get all unique values from a JavaScript array.

The filter Method

We can use an array instance’s filter method to filter out any duplicate values that are found.

For instance, we can write:

const onlyUnique = (value, index, arr) => {
  return arr.indexOf(value) === index;
}

const a = ['a', 1, 'a', 2, '1'];
const unique = a.filter(onlyUnique);

We have the onlyUnique function that we use as the callback for the filter method.

The callback for the filter method accepts the value that we’re iterating through as the first parameter.

The 2nd parameter is the index of the element we’re iterating through.

arr is the array we’re iterating through.

So we can call indexOf or arr to get the index of the first instance of value .

If it isn’t the same as index , then we know it’s a duplicate value.

We can pass the function into the filter method to get the unique value.

Therefore, unique is [“a”, 1, 2, “1”]

Converting to a Set and Back to an Array

Another way that we can remove duplicates from an array is to convert an array into a set and then convert the set back to an array.

We can convert a set to an array with the spread operator since a set is an iterable object.

For instance, we can write:

const a = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(a)];
console.log(unique)

We create a set with the Set constructor.

This will create a set, which doesn’t allow duplicate values inside it.

So all the duplicate values will be removed.

Then we use the spread operator to convert the set back to an array.

unique should be the same value as before.

Lodash

Lodash has the uniq method that returns an array with the duplicate values removed.

For instance, we can write:

const a = ['a', 1, 'a', 2, '1'];
const unique = _.uniq(a)
console.log(unique)

to remove all the duplicate items from a .

Conclusion

We can remove duplicate items from an array with sets and the spread operator.

Also, we can do the same thing with the filter and indexOf methods.

And we can also use Lodash to remove duplicate items from an array.

Categories
JavaScript Answers

How to Copy a JavaScript Array by its Values?

Copying JavaScript arrays is something that we’ve to do often in our apps.

In this article, we’ll look at how to copy a JavaScript array by its values.

Array.prototype.slice

We can use the slice method available in a JavaScript array instance.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.slice();
console.log(newArray);

The slice method returns a copy of the array it’s called on if no arguments are passed into it.

Spread Operator

Another way to copy an array’s entries into another array is to use the spread operator.

This is available since ES6.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = [...oldArray];
console.log(newArray);

We copy all the items from the oldArray into the newArray with the spread operator.

So newArray is the exact copy of oldArray .

Array.prototype.concat

We can also use the concat method to copy an array to a new array.

To use it, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = [].concat(oldArray);
console.log(newArray);

concat returns the array it’s called on with the array that’s passed into it as the argument.

Also, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = oldArray.concat();
console.log(newArray);

which also returns a copy of oldArray .

JSON.stringify and JSON.parse

We can use JSON.stringify and JSON.parse to make a copy of an array.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = JSON.parse(JSON.stringify(oldArray));
console.log(newArray);

JSON.stringify converts oldArray to a JSON string.

Then we use JSON.parse to convert the JSON string back to an array.

And then we assigned the returned value to newArray .

Array.from

Another way to copy an array is to use the Array.from method.

The method lets us create an array from other arrays or an array-like object.

To use it to copy an array we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = Array.from(oldArray);
console.log(newArray);

We just pass in the array we want to copy into the method and it’ll be copied.

Lodash

Lodash has the clone method to do a shallow clone of an object.

It also has the cloneDeep method to do a deep clone of an object.

We can use either one to copy an array.

For instance, we can write:

const oldArray = [1, 2, 3, 4, 5];
const newArray = _.clone(oldArray)
console.log(newArray);

or:

const oldArray = [1, 2, 3, 4, 5];
const newArray = _.cloneDeep(oldArray)
console.log(newArray);

to make a copy of oldArray and assign it to newArray .

Conclusion

There are many ways to copy an array into another one with JavaScript’s standard libraries.

We can also do the same thing with Lodash.

Categories
JavaScript Answers

How to Detect a Mobile Device with JavaScript?

With web apps being used on mobile devices more than ever, checking for a mobile device in a web app is something that we need to do often.

In this article, we’ll look at how to detect if a mobile device is being used to run a web app with JavaScript.

Use Agent Detection

One way to check for a mobile device is to check the user agent.

This isn’t the best way to check if a user is using a mobile device since user agent strings can be spoofed easily.

However, it’s still an easy way to check what device is being used by the user.

To get the user agent string, we can use the navigator.userAgent property.

For instance, we can write:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
  //...
}

We check for all the relevant keywords that indicate the user is using a mobile device with our web app with the regex.

Check Screen Size

We can also check the size of the screen that the user is loading the web app in.

For instance, we can write:

const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

if (isMobile) {
  //...
}

If max-width is 760px or less, then we know the user is loading the web app on a mobile device.

The pixels are scaled in a mobile device so that the screen width is less than 760px for mobile devices also.

Check for Touch Events

We can also check for touch events in our JavaScript code.

For instance, we can write:

const isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));

If the ontouchstart event is available in the browser, then it’s probably a mobile device since most mobile devices have touch screens.

The navigator.platform Property

The navigator.platform property also has a user agent string.

It’s more reliable than the navigation.userAgent property.

For instance, we can use it by writing:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // ...
}

Conclusion

We can detect whether a user is using a web app on a mobile device with JavaScript.

One way to check is to check the user agent.

Another way to check is to check screen sizes.

And we can also check if touch events are available in the browser.

Categories
JavaScript Answers

How to Merge Properties of Two JavaScript Objects Dynamically?

JavaScript objects have dynamic properties.

This means that we can merge the properties of 2 JavaScript objects dynamically.

This is an operation that’s done frequently.

In this article, we’ll look at how to merge properties of 2 JavaScript objects dynamically.

Spread Operator

The spread operator is available to objects since ES2018.

It lets us merge 2 objects’ properties together with ease.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = {
  ...obj1,
  ...obj2
};

The spread operator is the 3 dots.

It copies the p[roperies from obj1 and obj2 in the same order that they’re written.

Therefore, merged is {a: 1, b: 2} .

If 2 objects have the same properties, then the value of the last one that’s merged in overwrites the one that’s there previously.

For instance, if we have:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 2
}
const merged = {
  ...obj1,
  ...obj2
};

Then merged is {a: 2} .

Object.assign

The Object.assign method also lets us combine 2 objects together and return one merged object as the result.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = Object.assign(obj1, obj2);

Then merged is {a: 1, b: 2} .

The object in the first argument is mutation.

So if we want to return a new object with the properties of 2 objects without changing them, we pass in an empty array as the first argument:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = Object.assign({}, obj1, obj2);

Object.assign is available since ES6

for-in Loop

If the 2 ways above aren’t available, then we can use the for-in loop as the last resort.

It’s definitely not recommended since the 2 options above have been available for a few years.

And they’re much simpler and easier to use.

But if we need to use the for-in loop, we write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}

const merged = {}
for (const prop in obj1) {
  merged[prop] = obj1[prop];
}

for (const prop in obj2) {
  merged[prop] = obj2[prop];
}

We loop through all the properties of obj1 and obj2 with the for-in loop and put all the properties values into the merged object.

prop has the property name.

And so merged is:

{a: 1, b: 2}

Conclusion

We can use the spread operator and Object.assign to merge properties from different objects into one object.