3

For the following code I get this error:

burgerLines.map is not a function

HTML

<div class="burgerIcon">
  <div class="burgerLine"></div>
  <div class="burgerLine"></div>
  <div class="burgerLine"></div>
</div>

JS

const burgerLines = document.querySelectorAll('.burgerLine')

burgerLines.map((burgerLine) => {
  burgerLine.addEventListener('mouseover', (e) => {
    console.log('The burger is hovered')
  })
})

What is wrong with my code?

user1941537
  • 6,097
  • 14
  • 52
  • 99
  • 3
    `querySelectorAll` returns a NodeList, not an array, so it doesn't have a `.map` method. – VLAZ Apr 13 '20 at 11:49
  • 3
    you're trying to use `.map()` for iteration here anyway. I suggest you use `.forEach()`, as you're not using the result `.map()` _would_ give you. The `.forEach()` method _is_ part of the NodeList prototype – Nick Parsons Apr 13 '20 at 11:52
  • 2
    Thanks. Just saw your message. Yes, forEach is working. :-) – user1941537 Apr 13 '20 at 11:57

1 Answers1

3

The querySelectorAll method returns an array-like object called a node list.

These data structures are referred to as “Array-like”, because they appear as an array, but can not be used with array methods like map.

You could convert it to an array using Array.apply:

const burgerLines = document.querySelectorAll('.burgerLine');
const burgerLinesArray = Array.apply(null, burgerLines);

burgerLinesArray.map((burgerLine) => {
  burgerLine.addEventListener('mouseover', (e) => {
    console.log('The burger is hovered')
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="burgerIcon">
  <div class="burgerLine">-</div>
  <div class="burgerLine">-</div>
  <div class="burgerLine">-</div>
</div>

Or use forEach() instead as VLAZ commented since you don't need to manipulate that values.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
  • Thanks. This of course fix it. Another solution that I found after reading the answers was using forEach instead of map. It works too. – user1941537 Apr 13 '20 at 11:56
  • Yes, map is to manipulate the elements which you don't do. Foreach is a better option in this case, I've also updated the answer. – jeprubio Apr 13 '20 at 12:00
  • 2
    The querySelectorAll method returns an array-like object called a node list, which doesn't have the .map() method. But node-lists can be used with forEach() method. In your example we don't need to convert the burgerLine to an array and can still use it with forEach(). Alternatively, if we convert it, then we can use it with map() method. – user1941537 Apr 13 '20 at 12:35