Suppose I have the following HTML code:
<form id="myform" name="X" ... ><!-- the name is optional, may be undefined -->
<input type="text" name="name" value=""... >
</form>
<script>
let form = document.getElementById('myform');
// form.name can be either the name of the form or an instance of Element here
</script>
What would be the most reliable and cross-browser compatible way of getting the name of the form or null if it is not set?
I did some tests on Safari, so far my solution is this:
<script>
let form = document.getElementById('myform');
if (typeof form.name === 'string') {
// do the work
}
</script>
But I have no idea if that’s going to work on other browsers.
4
Answers
name
is just an attribute. So you can use:If the attribute exists, you will receive its value as a string, otherwise null.
See the compatibility of getAttribute().
getAttribute
will reliably give you the attribute value, ornull
if the attribute isn’t present; it won’t be fooled by a form field with the name"name
". Combine that with a truthiness check on the result and you’re good to go:Example with various permutations:
This is very, very basic functionality, so I wouldn’t expect any trouble with older browsers, regardless of one’s definition of "older".
Your current solution using
typeof form.name === 'string'
is a reasonable approach to check if thename
attribute is a string, and it should work in most modern browsers, including older versions.However, if you want a more standardized and cross-browser approach, you can use the
getAttribute
method:This ensures that you retrieve the value of the
name
attribute explicitly usinggetAttribute
. The condition then checks if the attribute exists (formName) and if its type is a string.This approach should work consistently across various browsers and is a good practice for dealing with attributes that might not be set or have different data types.
It is a very bad idea to give attribute name with ‘name’ as value.
In standard HTML (since 1993), the form element’s
name
attribute usage is made to access anyform
element into thedocument.forms
collection.Using a
name
as value [for attribute name] in any form children element will cause a syntax ambiguity and produce an obscurantist code.Prefer to do:
Deliberately coding syntactic ambiguities seems more suicidal than funny to me…