Categories
JavaScript Answers

How to Add or Remove Several Classes in One Single Instruction with classList?

Sometimes, we want to add or remove several classes in one single instruction with the classList API.

In this article, we’ll look at how to add or remove several classes in one instruction with classList .

Add or Remove Several Classes in One Single Instruction with classList

The add method takes one or more class name strings.

Therefore, we can use it to add more than one class at a time.

For instance, if we have the following HTML:

<div>

</div>

Then we can add more than one class by writing:

const div = document.querySelector('div')
div.classList.add("first", "second", "third");

If we have an array, then we can spread the entries as arguments:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add(...list);

And we can replace the spread operator with apply :

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.classList.add.apply(
  div.classList,
  list
);

Set the className Property

We can also set the className property to a string with multiple classes with each separated by a space.

For instance, we can write:

const div = document.querySelector('div')
const list = ['first', 'second', 'third'];
div.className += list.join(' ');

to do the same thing.

The existing classes will be overwritten.

Conclusion

We can use the classList.add method or set the className property to add multiple class names to an element.

Categories
JavaScript Answers

How to Make a JavaScript Function Wait Until an Element Exists Before Running it?

Sometimes, we want to wait until an element exists before running a JavaScript function.

In this article, we’ll look at how to make a JavaScript function wait until an element exists before running it.

Using the MutationObserver to Watch for Element to be Added to the DOM

We can use the MutationObserver constructor available with modern browsers to watch for an element appearing.

For instance, if we have the following HTML:

<div id='container'>

</div>

Then we can append a child element to it and watch it appear by writing:

const container = document.getElementById('container')
setTimeout(() => {
  const div = document.createElement('div')
  div.textContent = 'hello'
  div.id = 'hello'
  container.appendChild(div)
}, 2000)

const observer = new MutationObserver((mutations, obs) => {
  const hello = document.getElementById('hello');
  if (hello) {
    console.log(hello.innerText)
    obs.disconnect();
    return;
  }
});

observer.observe(document, {
  childList: true,
  subtree: true
});

We call setTimeout with a callback that appends a div as the child of the div with ID container .

Then we invoke the MutationObserver constructor with a callback that has the mutation and obs parameters.

obs is the returned observer.

In the callback, we try to get the element with ID hello .

If it exists, then we get the innerText property value of the element.

And then we call disconnect stop watching for changes in the DOM.

Then we call observer.observe to watch for changes in the document .

childList is set to true to watch for adding or removing of the elements.

subtree is also set to true to watch for child element changes.

Conclusion

We can use the MutationObserver constructor to easily watch for changes to the DOM.

Therefore, we can use it to wait for an element to appear before running any code.

Categories
JavaScript Answers

How to Use Regular Expression to Get Strings Between Parentheses with JavaScript?

Sometimes, we may want to get the substrings in a JavaScript string that is between parentheses.

In this article, we’ll look at how to use regular expressions to get strings between parentheses with JavaScript.

Use Regular Expression to Get Strings Between Parentheses with JavaScript

We can use the match method to get the substrings in a string that match the given regex pattern.

For instance, we can write:

const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)\+)\)/g;
const matches = [...txt.match(regExp)];
console.log(matches)

We create the regExp regex that matches anything between parentheses.

The g flag indicates we search for all substrings that matches the given pattern.

Then we call match with the regExp to return an array of strings that are between the parentheses in txt .

Therefore, matches is [“($500)”, “($600)”] .

We can also exclude strings with inner parentheses with:

/\(([^()\]*)\)/g

With the matchAll method, we can also get the substrings that are inside the parentheses without the parentheses.

To use it, we write:

const txt = "I expect five hundred dollars ($500). and new brackets ($600)";
const regExp = /\(([^)\]+)\)/g;
const matches = [...txt.matchAll(regExp)].flat();
console.log(matches)

We call flat to flatten the array.

And so matches is [“($500)”, “$500”, “($600)”, “$600”] .

Conclusion

We can use regular expressions to get strings between parentheses with JavaScript.

Categories
JavaScript Answers

How to Get the Value of a Checked Checkbox with JavaScript?

Sometimes, we may want to get the value of a checked checkbox within our web app.

In this article, we’ll look at how to get the value of a checked checkbox with JavaScript.

Get All Checked Checkboxes

We can use plain JavaScript to get all the checked checkboxes.

For instance, if we have the following checkboxes:

<input type="checkbox" value="1" name="mailId[]" checked>1
<input type="checkbox" value="2" name="mailId[]" checked>2
<input type="checkbox" value="3" name="mailId[]">3

Then we can select all the checkboxes that are checked and get their values with:

const checked = document.querySelectorAll('input[type="checkbox"]:checked');
console.log([...checked].map(c => c.value))

We add the :checked pseudoselector to select all the checked checkboxes.

The first 2 checkboxes have the checked attribute, so we should get the value of the first 2 with it.

Then we log the value property.

We spread the checked NodeList into an array.

Then we call map with a callback to return the value property of each checkbox that is checked.

Therefore, the console log should log [“1”, “2”] .

Conclusion

We can get the value of all the checked checkboxes with plain JavaScript.

Categories
JavaScript Answers

How to Sort Alphanumeric Strings with JavaScript?

Sometimes, we want to sort alphanumeric strings with JavaScript.

In this article, we’ll look at how to sort alphanumeric strings with JavaScript.

String.prototype.localeCompare

We can use the string localeCompare method to compare strings so we can sort them.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const sorted = arr.sort((a, b) => {
  return a.localeCompare(b, undefined, {
    numeric: true,
    sensitivity: 'base'
  })
})
console.log(sorted)

We call localeCompare to compare a and b naturally.

We set numeric to true to compare the numerical part of a and b .

sensitivity is set to 'base' to compare the case and the alphabet.

Therefore, sorted is:

["19asd", "123asd", "12345asd", "asd12", "asd123"]

Use Intl.Collator

Also, we can use the Intl.Collator constructor to create a collator instance which has the compare method to compare 2 strings.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: 'base'
});
const sorted = arr.sort((a, b) => {
  return collator.compare(a, b)
})
console.log(sorted)

The options are the same as localeCompare .

compare takes the 2 strings we want to compare.

Then sorted is the same result as before.

Conclusion

We can sort alphanumeric strings naturally with native JavaScript methods.