In this short post I will explain the difference between attributes and properties in HTML. The
.prop() function introduced in jQuery 1.6 raised a lot of questions about the difference and I hope this post will help you to understand it.
What is an attribute?
Attributes carry additional information about an HTML element and come in
name=”value” pairs. Example:
<div class=”my-class”></div>. Here we have a
div tag and it has a
class attribute with a value of
What is a property?
Property is a representation of an attribute in the HTML DOM tree. So the attribute in the example above would have a property named
className with a value of
Our DIV node |- nodeName = "DIV" |- className = "my-class" |- style |- ... |- ...
What is the difference between attribute and property?
Here is a visual representation:
HTML DOM <input value="default" /> value = default ---------------- Current values: Attribute: "default" Property: "default"
Assume user inputs his name "Joe" into the inputbox. Here are what attribute and property values of an element will be.
HTML DOM <input value="default" /> value = Joe ---------------- Current values: Attribute: "default" Property: "Joe"
As you can see, only element’s property is changed, because it is in the DOM and dynamic. But element’s attribute is in HTML text and can not be changed!
I hope this helps to understand the difference between attributes and properties. If you have any questions please leave them on jQueryHowto Facebook page.
Also, stay tuned for the next post about the difference between
jQuery.prop() and when to use one over another.