What are the differences between properties and attributes in JavaScript?
When we write HTML elements, we write attributes with the element. Once the browser parses the HTML elements, it creates a DOM node object.
Let us consider the following HTML element:
<input type="text" value="Joe Smith" /> // The input element has 2 attributes (type and value).
When the browser parses this code, an HTMLInputElement object will be created, and this object will contain properties like accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, etc.
The properties of a DOM node object are the properties of that object, and attributes are the elements of the attributes property of that object.
When the user manually changes the value of the input box, the value property will reflect this change but the attribute will remain the initial value.
If the user changes the value property to ‘Cathy Cassidy’, then it shows the following:
Instead, it is the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs “John” into the input box, then:
console.log(inputObj.value) // Cathy Cassidy
But the attribute remains the initial value:
console.log(inputObj.getAttribute('value')) // Joe Smith