-2

Screenshot

enter image description here

Im a begginer of Javascript and its a bit obvious what im trying to do, its a simple code but it tells me always 2 things, addEventListenerenter code here` is not a function" and "add event listener undefined" tried Loops, tried changing Elements for Element tried telling which from the elements is fromm [number (i know first is cero)], changed place of script, and tried giving boolean values to face, Help.

Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

0

Don't paste screenshots of code, paste your actual code instead.

The problem is that getElementsByClassName returns an HTMLCollection, not a single element, so you can't assign a listener to the collection: select a single element first.

The getElementsBy* methods return HTMLCollections, which can be difficult to work with. Consider using querySelectorAll instead, which returns a static NodeList - unlike an HTMLCollection, it can be iterated over directly, it won't change while it's being iterated over, and it's much more flexible.

Try something like this:

document.querySelectorAll('.alex').forEach((alex) => {
  alex.addEventListener('mousemove', () => document.querySelector('.pipo').textContent += 'mooove';
});

Note that NodeList.forEach is something new-ish, supported as of the past few years - to support ancient browsers, use a plain for loop or a polyfill. (array methods are generally superior to for loops: no manual iteration, better abstraction, function parameters)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thx dude!, so if i change from my code only my ElementsBy for QuerySelector will it still work? or i have to loop it like that? – Lechuga Violenta Apr 11 '18 at 04:13
  • You put a `for` loop in there, so I assumed you were trying to iterate over every `.Alex` (though I only see one of them in your HTML? if you're only ever going to have one, then yes, use querySelector instead) – CertainPerformance Apr 11 '18 at 04:17