1

Using javascript - How do I find an element in a group of elements that share the same className that does not have a specific event attached to it.

var items = document.getElementsByClassName("myInputs");

How do I query the result - items to find out which of these elements do not have a keypressed event attached to them ?

1 Answers1

0

A working solution (Edit: This does not work if event has been attached with addEventListener as pointed in comment and explained here):

var items = document.getElementsByClassName("myInputs");
var elementsWithoutKeyPress = Array.prototype.slice
    .call(items)
    .filter(function(item) {
        return !item.onkeypress;
    });

Edit (from comment suggestion): Array.prototype.slice.call is (more or less) an idiom to call Array methods on non-array containers. And here you have the documentation of filter function.

raul.vila
  • 1,984
  • 1
  • 11
  • 24
  • 1
    It is not too wise to answer "try this", as it incourages lazy people who just don't want to do their homework. I'd rephrase your (correct) answer that `Array.prototype.slice.call` is (more or less) an idiom to call Array methods on non-array containers and add a link on `.filter` method. Maybe I'd add some ilustrating code, which should not be a copy-paste solution, at least not at this kind of questions. Just don't omit the explanation. – Jan Turoň Apr 15 '18 at 15:19
  • Jan, I edited the answer, thanks for the suggestions. Julian, you're welcome :). – raul.vila Apr 15 '18 at 15:23
  • 1
    This works, but not if the event was attached using `addEventListener`, which is a pretty big potential problem IMO... – lonesomeday Apr 15 '18 at 15:32
  • Thanks lonesomeday, you're right, bug demo: https://jsfiddle.net/cCrul/uzd2qfLb/ advice added in the answer – raul.vila Apr 15 '18 at 15:41