Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the 'map is not a function' error in Javascript

Tags:

javascript

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".

like image 287
Samuel Tengan Avatar asked Jan 23 '26 02:01

Samuel Tengan


1 Answers

document.querySelectorAll returns a NodeList which should be converted to real Array before using map()

The Document method querySelectorAll() returns a static (not live) NodeList representing 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.

like image 166
Maheer Ali Avatar answered Jan 24 '26 19:01

Maheer Ali