How to get the form that owns a div?

2019-08-30 04:25发布

问题:

Different from input elements, div elements only have the "global attributes". I have a function where I get an element and store its data in the localStorage, together with the id of the form that it belongs to (so I can store many pages/forms in the same storage space):

function store(what) {
    var F = what.form;
    if (what.id.substr(0,3) == 'div') {
        localStorage.setItem(F.id+'.'+what.id,what.innerHTML);
    } else
        localStorage.setItem(F.id+'.'+what.name,what.value);
    }
}

The problem is, since divs don't have a form attribute, is there any other way to get it from the element alone?

回答1:

Assuming you mean "contains", then just recursively check element.parentNode until you find a form element or parentNode is null.

function ancestorForm(element) {
    if (element === null || element.tagName.toLowerCase() === "form") {
        return element;
    } else {
        return ancestorForm(element.parentNode);
    }
}