Skip to content
Advertisement

Form elements overwrite default properties of a form object [closed]

Let’s say we have a form with the following inputs: (and yes, what if we really want to have those names)

<form id="form-id">
    <input type="text" name="submit" />
    <input type="text" name="elements" />
    <input type="text" name="id" />
    <input type="text" name="addEventListener" />
</form>

Now, if we try to access form properties, all we get is input objects:

var form = document.getElementById('form-id');

form.elements; // will be <input type="text" name="elements" /> instead of a list of elements

same problem with:

form.submit;
form.id;
form.addEventListener;

and all other default properties of a form object.

I do understand that we could find some other way to access those properties… but what should we do with those that we can’t?

Your suggestions.

Advertisement

Answer

Of course the easiest way is to thumb-down the question and forget about it. But I went further and found out how to solve this problem. So I’ll just leave it here. IE9+

HTMLFormElement.prototype.getRealAttribute = function(name) {
    var form = this;
    var tmpForm = document.createElement('FORM');

    /* if it's not overridden */
    if (Object.prototype.toString.call(tmpForm[name]) === Object.prototype.toString.call(form[name])) {
        if (Object.prototype.toString.call(tmpForm[name]) === "[object Function]") {
            return form[name].bind(form);
        }
        return form[name];
    }

    /* if it's overridden function */
    if (HTMLFormElement.prototype[name]) {
        return HTMLFormElement.prototype[name].bind(form);
    }

    /* if it's an attribute */
    if (form.attributes[name]) {
        return form.attributes[name].value;
    }

    /* if it's an overridden property */
    var fieldSet = document.createElement('FIELDSET');
    fieldSet.innerHTML = form.innerHTML;

    return fieldSet[name] || null;
};
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement