JavaScript Array.from() method

The Array.from() method in JavaScript is used to create a new array instance from an array-like or iterable object. This method is typically used to convert a non-array object (such as a NodeList or Set) into an array, so that array methods can be used on it.

Here is an example of how the Array.from() method works:

const divs = document.querySelectorAll('div');

// convert the NodeList into an array
const array1 = Array.from(divs);

// use the map() array method on the array
const result = array1.map(div => div.innerHTML);

// the result will be an array containing the inner HTML of each div

In the code example above, we first use the querySelectorAll() method to get a NodeList of all div elements in the document. We then use the Array.from() method to convert the NodeList into an array. This allows us to use array methods on the divs object, such as the map() method, which we use to create a new array containing the inner HTML of each div element.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: