I'm looping through all anchor tag in an HTML with a class (.add-to-cart) to change text content to shop now, using map() but i am getting an error that says .map is not a function.
<!--HTML CODE -->
<div class="four columns">
<div class="card">
<a href="#" class="u-full-width button-primary button input add-to-cart" data-id="5">Add to Cart</a>
</div>
</div> <!--.card-->
<div class="four columns">
<div class="card">
<a href="#" class="u-full-width button-primary button input add-to-cart" data-id="5">Add to Cart</a>
</div>
</div> <!--.card-->
<div class="four columns">
<div class="card">
<a href="#" class="u-full-width button-primary button input add-to-cart" data-id="5">Add to Cart</a>
</div>
</div> <!--.card-->
//JAVASCRIPT CODE
const addCartBtns = document.querySelectorAll('.add-to-cart');
addCartBtns.map(function(cartBtn){
console.log(cartBtn.textContent="shop now");
});
I expect the output to change text content of anchor tags to "shop now".
document.querySelectorAll returns a NodeList which should be converted to real Array before using map()
The Document method
querySelectorAll()returns a static (not live)NodeListrepresenting a list of the document's elements that match the specified group of selectors
You can use Spread Operator
const addCartBtns = [...document.querySelectorAll('.add-to-cart')]
Or you can can use Array.from
const addCartBtns = Array.from(document.querySelectorAll('.add-to-cart'))
Notice that you are using map(). map() is used when you want to create a new array bases on the values of existing array of same length. Here you are modifying the array. So you can use forEach
addCartBtns.forEach(function(cartBtn){
console.log(cartBtn.textContent="shop now");
});
Note:forEach will work fine if NodeList is not converted to array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With