This content originally appeared on Go Make Things and was authored by Go Make Things
Last week, one of my students tipped me off to something that had somehow escaped my notice until now: the Array.from()
method accepts an optional second argument that runs an Array.map()
over the thing you’re converting into an array.
For example, let’s say you were trying to create a table of contents for your site based on the H2 headings on the page.
You could use document.querySelectorAll()
to get a NodeList of all the H2 headings. And you can use the Array.map()
and Array.join()
methods to take each heading, create a new array with HTML strings, and join them together into one string.
But first, you have to convert the NodeList into an array.
let toc = document.querySelector('#table-of-contents');
let headings = document.querySelectorAll('h2');
toc.innerHTML =
'<ul>' +
Array.from(headings).map(function (heading) {
return `<li><a href="#${heading.id}">${heading.textContent}</a></li>`;
}).join('') +
'</ul>';
But, you can actually skip the separate Array.map()
method and map the new values while converting the NodeList with Array.from()
.
toc.innerHTML =
'<ul>' +
Array.from(headings, function (heading) {
return `<li><a href="#${heading.id}">${heading.textContent}</a></li>`;
}).join('') +
'</ul>';
Neat trick! Situational, but useful.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-03-09T15:30:00+00:00) The Array.from() method in vanilla JS also lets you update values. Retrieved from https://www.scien.cx/2021/03/09/the-array-from-method-in-vanilla-js-also-lets-you-update-values/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.