required
is a reflected property (like id
, name
, type
, and such), so:
element.required = true;
…where element
is the actual input
DOM element, e.g.:
document.getElementById("edName").required = true;
(Just for completeness.)
Re:
Then the attribute’s value is not the empty string, nor the canonical name of the attribute:
edName.attributes.required = [object Attr]
That’s because required
in that code is an attribute object, not a string; attributes
is a NamedNodeMap
whose values are Attr
objects. To get the value of one of them, you’d look at its value
property. But for a boolean attribute, the value isn’t relevant; the attribute is either present in the map (true) or not present (false).
So if required
weren’t reflected, you’d set it by adding the attribute:
element.setAttribute("required", "");
…which is the equivalent of element.required = true
. You’d clear it by removing it entirely:
element.removeAttribute("required");
…which is the equivalent of element.required = false
.
But we don’t have to do that with required
, since it’s reflected.