Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about HTMLCollections and named properties, continue to use?

When referring to elements in HTML forms I often use the name/value of the name attribute. So, if the name of the form is "form01", I refer to the form writing document.forms.form01. Here is an example:

let title = document.forms.form01.title;
console.log(title.value);
<form name="form01">
  <input type="text" name="title" value="Hello World">
</form>

The document.forms is a HTMLCollection, but in the documentation for the DOM Standard #interface-htmlcollection it says nothing about the possibility of using a name directly as a property (I think it is called a "named property") on a collection like that -- like when I use document.forms.form01 to refer to the form element. On the contrary the documentation actually notes that this is "a historical artifact" -- so, should I avoid using it?

Can you help me find documentation for this? Either that it is a (nice) feature that can be used or that it is something that should be avoided.

like image 791
chrwahl Avatar asked Oct 27 '22 10:10

chrwahl


1 Answers

If it's not marked as a deprecated or obsolete feature, you absolutely can continue to use it!

Additional detail on MDN Web Docs about HTMLCollection states the following:

The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.


As for named properties in HTMLCollection (as @Kaiido pointed out), this section states:

The supported property names are the values from the list returned by these steps:

  1. Let result be an empty list.

  2. For each element represented by the collection, in tree order:

    1. If element has an ID which is not in result, append element’s ID to result.

    2. If element is in the HTML namespace and has a name attribute whose value is neither the empty string nor is in result, append element’s name attribute value to result.

  3. Return result.

Also note that NodeList falls under the same section (Old-style collections) as HTMLCollection. See NodeList on MDN Web Docs.


The previous mention of [LegacyUnenumerableNamedProperties] (as @Kaiido pointed out) only indicates that the named properties are unenumerable (i.e., using Array.from will only return the index items).

like image 133
phentnil Avatar answered Oct 30 '22 00:10

phentnil