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>
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:
const hrefs = [];
for (const anchor of document.querySelectorAll(".el")) {
hrefs.push(anchor.getAttribute("href"));
}
console.log(hrefs); // ["italy.php", "france.php", "japan.php", "china.php"]
<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>