Moshe
Moshe

Reputation: 6991

Select Form with Data Attribute: JavaScript

I have a number of forms each of which have a data attribute of data-validate. I know that I can select those forms with the following query: document.querySelectorAll('form[data-validate]').

I have, however, a two-fold question. First, how could I select those same forms using document.forms. Secondly, is one method preferable over the other? That is, does it make a difference whether or not I use document.forms or document.querySelectorAll?

Thanks.

Upvotes: 0

Views: 476

Answers (1)

Quentin
Quentin

Reputation: 943591

First, how could I select those same forms using document.forms

document.forms only allows addressing a form by its index, name or id so, other than looping over all the values in document.forms and testing each one in turn to see if it has a data-validate attribute: You can't.

Secondly, is one method preferable over the other?

Preference is a matter of opinion. (Although the one involving less code that leaves the filtering to native code would fit more criteria of "better").

Upvotes: 1

Related Questions