Search code examples
javascriptdomgetelementsbyname

Why is getElementsByName only usable from document in JavaScript?


I would like to do something like this:

var form = document.getElementsByTagName("form")[0];
var form_element_list = form.getElementsByName("foo");

But alas, it seems that getElementsByName can only be run from document (see MDN).

Question:
why is it only possible to search from the document level? Especially as name attributes are mostly used in forms.

Thanks!


Solution

  • why is it only possible to search from the document level?

    For historical reasons? We don't really know. However, names are global identifiers just as like as ids in document.getElementsById, only they are not unique.

    Especially as name attributes are mostly used in forms.

    You would use the form's .elements collection for that purpose, it can be adressed with names as well.