You will find the answers buried inside HTML specs. I first want you to have a look at the attributes and properties of the input
element (heading "Content attributes" and "DOM interface") and the section about attribute reflection (first paragraph).
You will notice that all attributes have corresponding properties and manipulating a property will change the attribute it reflects. It is worth noting that:
(1) An attribute could be reflected by a property with a slightly different name. The classical example is the class
attribute which is reflected by className
property and for
attribute which is reflected by htmlFor
property.
(2) Likewise the checked
attribute is reflected by defaultChecked
property whereas the checked
property represents the internal state of the checkbox irrespective of the checked
attribute. This has always caused confusion among programmers (and book authors). The difference is explained at the end of this answer.
(3) Made-up attributes (such as the "book" attribute in your example) will not generate corresponding property and vice-versa. For this purpose the HTML specs describe a mechanism called data attributes and dataset
property.
A related question, if I want to get or set a value on a DOM element,
should I get/set the property
or the attribute
?
Depends. For example both of the following produce identical result and HTML:
document.getElementById("div-1").title = "Hello";
document.getElementById("div-1").setAttribute("title") = "Hello";
However, for form elements you should manipulate the state instead of attribute. Suppose you have this HTML markup:
<input type="checkbox" id="checkbox-1">
And you execute either of the following:
document.getElementById("checkbox-1").defaultChecked = true;
document.getElementById("checkbox-1").setAttribute("checked", "checked");
And here is the result:
<input type="checkbox" id="checkbox-1" checked="checked">
But whether the checkbox actually get checked depends on the dirtiness of the control (i.e. if its state was changed at some point). For form elements you would normally manipulate the properties that correspond to the internal state:
document.getElementById("checkbox-1").checked = true;