- Attributes are defined by HTML, all definitions inside HTML tag are attributes.
- The type of attributes is always string.
- Properties belong to DOM, the nature of DOM is an object in JavaScript. We can get and set properties as we do to a normal object in JavaScript and properties can be any types.
- Non-custom attributes have 1:1 mapping onto properties, like:
id
,class
,title
, etc. - Non-custom property (attribute) changes when corresponding attribute (property) changes in most cases.
- Attribute which has a default value doesn't change when corresponding property changes.
It is recommended to use properties in JavaScript as it's much easier and faster. Especially for boolean type attributes like: checked
, disabled
and selected
, browser automatically converts them into boolean type properties.
<input id="test" class="blue" type="radio" />
// get id
document.getElementById('test').id;
// set class
document.getElementById('test').className = 'red';
// get and set radio control status
document.getElementById('test').checked;
document.getElementById('test').checked = true;
// get id
document.getElementById('test').getAttribute('id');
// set class
document.getElementById('test').setAttribute('class', 'red');