Javascript: how to distinguish the selected list of elements and form

Here are the scripts: http://jsbin.com/itusut/6/edit

Hi, I have a function:

function on(t, e, f) { if ( e.length ) { var l = e.length, n = 0; for ( ; n < l; n++ ) { e[n].addEventListener(t, f, false) } } else { e.addEventListener(t, f, false); } } 

if we do var handle = document.getElementsByClassName('some-class'); then handle is node.

if we do var handle = document.getElementById('an-id'); then handle is the only node.

The problem is that when I select <form id="login-form"> , it returns an array of more than one element.

So my on function fails. The function uses the elm.length filter. Everything is fine except for <form> . How to fix it? I know that elm.length does not work properly in a single node <form> element.

Will you help Thank you very much

+6
source share
1 answer

Form elements have the length property (specify the number of fields in the form). The code you use does not accurately determine if this element is a DOM node, so it assumes that the form is a collection of DOM nodes.

If you need to bind elements, you are probably best off passing an array object or an array, so the function always iterates through the collection.

It can be as simple as moving a parameter to an array:

 on('click', [formElement], callback); 

Updated version on , where only lists are supported:
 function on(type, elements, callback) { var length, i; length = 0; if (elements && elements.length) { length = elements.length; } for (i = 0; i < length; i += 1) { elements[i].addEventListener(type, callback, false); } } 
+6
source

Source: https://habr.com/ru/post/951770/


All Articles