Categories
JavaScript Answers

How to Loop Through All DOM Elements on a Page with JavaScript?

Sometimes we want to loop through all DOM elements on a page with JavaScript.

In this article, we’ll look at how to loop through all DOM elements on a page with JavaScript.

Select All Elements with document.getElementsByTagName

We can select all elements on a page with the document.getElementsByTagName method.

For instance, if we have the following HTML:

<div>
  <span>hello world</span>
</div>
<p>
  how are you
</p>

Then we can loop through all of them by writing:

const allEls = document.getElementsByTagName("*");
for (const el of allEls) {
  console.log(el)
}

We select all elements by calling document.getElementsByTagName with '*' .

And then we can loop through all the returned elements with the for-of loop.

Select All Elements with document.querySelectorAll

We can select all elements on a page with the document.querySelectorAll method.

For instance, if we have the following HTML:

<div>
  <span>hello world</span>
</div>
<p>
  how are you
</p>

Then we can loop through all of them by writing:

const allEls = document.querySelectorAll("*");
for (const el of allEls) {
  console.log(el)
}

We select all elements by calling document.querySelectorAll with '*' .

And then we can loop through all the returned elements with the for-of loop.

Conclusion

We can use the document.getElementsByTagName or document.querySelectorAll method to get all elements on a page.

Then we can loop through them all with the for-of loop.

Categories
JavaScript Answers

How to Add an Ordinal Suffix to a JavaScript Number?

Sometimes, we want to add an ordinal suffix to a JavaScript number.

In this article, we’ll look at how to add an ordinal suffix to a JavaScript number.

Use the Intl.PluralRules Constructor

We can add the correct ordinal suffix to a JavaScript number easily with the Intl.PluralRules constructor.

For instance, we can use it by writing:

const ordinal = (number) => {
  const ordinalRules = new Intl.PluralRules("en", {
    type: "ordinal"
  });
  const suffixes = {
    one: "st",
    two: "nd",
    few: "rd",
    other: "th"
  };
  const suffix = suffixes[ordinalRules.select(number)];
  return (number + suffix);
}
console.log(ordinal(101))

We create the ordinal function with the number parameter.

In the function, we create the ordinalRules object with the Intl.PluralRules constructor.

The first argument is 'en' which gets the rules for the English locale.

The 2nd argument is an object with type set to 'ordinal' which lets us return the ordinal rules.

Next, we create the suffixes object with the rules.

Then we call the select method with the number to return 'one' , 'two' , 'few' or 'other' .

So the suffix would be one of the property values in suffixes .

And finally, we return the number and suffix concatenated together.

Therefore the console log should log '101st' .

Conclusion

We can use the Intl.PluralRules constructor to add an ordinal suffix to a JavaScript number.

Categories
JavaScript Answers

How to Clone an Object with JavaScript?

Sometimes we want to clone an object in our JavaScript code.

In this article, we’ll look at how to clone an object with JavaScript.

Use the Object.assign Method

One way to clone a JavaScript object is to use the Object.assign method.

For instance, we can write:

const obj = {
  a: 1
};
const copy = Object.assign({}, obj);
console.log(copy);

We call Object.assign with an empty object and obj to copy the properties of obj onto the empty object and return it.

Then copy has the same content as obj .

Use the Spread Operator

Another way to clone an object is to use the spread operator.

It works the same way as Object.assign .

For example, we can use it by writing:

const obj = {
  a: 1
};
const copy = {
  ...obj
};
console.log(copy);

Then we get the same result as the previous example.

Use the Lodash cloneDeep Method

If we need to deep clone an object, then we can use the Lodash cloneDeep method to do the cloning.

It’ll clone properties at all levels instead of just the top level.

For instance, we can use it by writing:

const obj = {
  a: 1
};
const copy = _.cloneDeep(obj);
console.log(copy);

Then copy is a deep copy of obj .

Conclusion

We can copy an object with the Object.assign method or the spread operator.

To deep clone an object, we can use the Lodash cloneDeep method.

Categories
JavaScript Answers

How to Replace a DOM Element in Place Using JavaScript?

Sometimes, we want to replace a DOM element in place with JavaScript.

In this article, we’ll look at how to replace a DOM element in place with JavaScript.

Use the parentNode.replaceChild Method

We can replace a DOM element in place with JavaScript by getting the parent of the element we want to replace.

Then we can call the replaceChild method on it to replace the element in place of the current child element of the parent.

For instance, if we have the following HTML:

<div>  
  hello world  
</div>

Then we can do the replacement by writing:

const div = document.querySelector("div");  
const span = document.createElement("span");  
span.innerHTML = "hello james";  
div.parentNode.replaceChild(span, div);

We get the div with document.querySelector .

Then we create a span that we want to replace the div with with document.createElement .

Next, we set the content of the span by setting the innerHTML property.

And finally, we call div.parentNode.replaceChild with the span and the div to replace the div with the span.

Now we should see ‘hello james’ in place of ‘hello world’

Use the replaceWith Method

An easier way to replace an element with another is to use the replaceWith method.

To use it, we write:

const div = document.querySelector("div");  
const span = document.createElement("span");  
span.innerHTML = "hello james";  
div.replaceWith(span);

In the last line, we call div.replaceWith with span to replace the div with the span .

And we get the same result as the previous example.

Conclusion

We can replace a DOM element in place by getting the parent node of the element we want to replace and call replaceChild on the parent node.

Or we can call the replaceWith on the element we want to replace and pass in the element we want to replace as the argument.

Categories
JavaScript Answers

How to Loop Through Each Item in a JavaScript FileList?

Sometimes, we want to loop through each item in a JavaScript file list.

In this article, we’ll look at how to loop through each item in a JavaScript file list object.

Convert the FileList Object with the Array.from Method and Use the Array.prototype.forEach Method

One way to let us loop through each item in a file list object is to convert it to an array with the Array.from method.

Then we can use the forEach method on it to loop through the file list entries.

For instance, if we have the following file input:

<input type='file' multiple>

Then we can get the input and listen to the change event of the file input to get the selected files after they’re selected:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  Array.from(input.files)
    .forEach(file => {
      console.log(file)
    });
})

The file input has the multiple attribute so that we can select multiple files.

We call addEventListener on the input to add a change listener to it.

We call Array.from method to convert the input.files file list to an array with the selected files.

input.files is the file list object with the selected files.

Then we can call the forEach method to loop through each file.

Convert the FileList Object with the Spread Operator and Use the Array.prototype.forEach Method

Another way to convert the file list object to an array is to use the spread operator.

This works since a file list is an iterable object.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  [...input.files]
  .forEach(file => {
    console.log(file)
  });
})

to spread the input.files entries into an array.

Then we can call forEach on it as we did before.

Use the for-of Loop

Since the file list object is an iterable object, we can also use the for-of loop on it to loop through each file list entry.

For instance, we can write:

const input = document.querySelector('input');
input.addEventListener('change', () => {
  for (const file of input.files) {
    console.log(file)
  }
})

to loop through each entry of input.files with the for-of loop.

Conclusion

We can convert the file list object to an array and use the forEach method or use the for-of loop to loop through each item in the file list.