let titleElements = document.querySelectorAll('.article .title') let titles = Array.from(titleElements).map( t => t.textContent ); console.log(titles);
The Array.from()
method in JavaScript is a powerful and versatile tool that can convert array-like objects into true Arrays. This becomes relevant when you want to access Array methods on structures that aren't true Arrays themselves, such as the NodeList returned by DOM element selection methods.
For instance, let's say we have the following script:
let titleElements = document.querySelectorAll('.article .title');
let titles = Array.from(titleElements).map(t => t.textContent);
console.log(titles);
In this code, document.querySelectorAll('.article .title')
returns a NodeList of all elements in the document that have the class of 'title' and are children of an element with the class 'article'. While this NodeList may look and feel similar to an Array, it isn't a true Array. As a result, JavaScript Array methods, such as map()
, are not available to it.
So, when we want to use Array methods like map()
, filter()
, reduce()
, etc. on a NodeList (or any array-like object), we must first convert it into a real Array. That's where Array.from()
comes into play. We use Array.from(titleElements)
to create a new Array from the NodeList titleElements
. This new Array then becomes the context for the map()
method that follows, enabling us to transform the text content of every title element into a neat list (titles
).
The versatility of Array.from()
lies not just in its ability to convert array-like objects to real Arrays, but also in handling Generators or iterable objects, or something as simple as converting a string into an array of characters.
In conclusion, the use of Array.from()
is not just about being 'hip'; it's a practical way of enhancing the versatility of your JavaScript code. Hence, it should feature prominently in your JavaScript best practices toolkit! It's especially useful when you need to manipulate HTML collections or NodeLists as if they were full-fledged Arrays.