i have this code and i want to get a new array with the href attribute of each element in the array; maybe there is a different way to do it
let countries = document.querySelectorAll('.el');
let countriesList = Array.prototype.slice.call(countries);
let arra = countriesList.map(link);
function link() {
for(let i = 0; i < countriesList.length; i++) {
countriesList[i].getAttribute('href');
}
}
console.log(arra)
<div>
<a class='el' href='italy.php'>Italy</a>
<a class='el' href='france.php'>France</a>
<a class='el' href='japan.php'>Japan</a>
<a class='el' href='china.php'>China</a>
</div>
4
Answers
You can convert the nodelist to an array and use map to get array of
href
A function passed to
map
is called once per element and must return a valueYou could also skip map
Your function link() does not return anything and has an unnecessary loop.
Also
Array.prototype.slice.call(countries);
is no longer an elegant way to get an array from a collection. Array.from is by far the most elegant and descriptive way. AND it takes a function to run while mapping! (Thanks Nick)Here is your fixed code still using a separate function to pass to the map-function of Array.from
You can avoid iterating the collection more than once by instantiating an empty array, then pushing each value into it in a
for...of
loop: