Categories
JavaScript Answers

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.

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.

Categories
JavaScript Answers

How to Get an Element’s Top Position Relative to the Browser’s Viewport?

Sometimes, we may want to get an element’s top position relative to the browser’s viewport.

In this article, we’ll look at ways to get an element’s top position relative to the browser’s viewport.

Use the getBoundingClientRect Method

We can use the getBoundingClientRect method to get an element’s position relative to its viewport.

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
console.log(t, l)

We get the div with querySelector .

Then we call getBoundingClientRect on it to get an object with the top and left properties.

top has the position relative to the top of the viewport.

left has the position relative to the left side of the viewport.

Both are in pixels.

If we want to take scrolling into account, then we add the scrollY value to top and scrollX value to left .

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
const {  
  scrollX,  
  scrollY  
} = window  
const topPos = t + scrollX  
const leftPos = l + scrollY  
console.log(topPos, leftPos)

to include the scroll position with the element’s position.

Conclusion

We can get the element’s position relative to the viewport by using the getBoundingClientRect method.