A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
HTML Attributes
Syntax:
<body onload="foo()">
DOM Properties
Syntax:
document.body.onload = foo;
Using jQuery
If we have:
<!-- HTML --> <input class-gns="brand">
// jQuery $("input").attr("data-gns"); // return "brand" $("input").prop("data-gns"); // return "undefined" because it is not in the DOM. // It's trying to get [HTMLInputElement].data-gns
See a real example:
JavaScript HTMLvar $e = $("input");
function get_html() {
return "<ul>" +
"<li>id prop: " + $e.prop("id") + "</li>" +
"<li>id attr: " + $e.attr("id") + "</li>" +
"<li>data-* prop: " + $e.prop("data-gns") + "</li>" +
"<li>data-* attr: " + $e.attr("data-gns") + "</li>" +
"<li>checked prop: " + $e.prop("checked") + "</li>" +
"<li>checked attr: " + $e.attr("checked") + "</li>" +
"</ul><br>";
};
// (1)
// id) exists in the HTML and in the DOM: it has the same interpretation
// data-*) exists only in the HTML: when the browser renders the HTML it defines it as undefined because there is not a DOM interpretation
// checked) exists in the HTML and in the DOM: it has a different interpretation
var html_ = get_html();
// (2)
$e.prop("id", "id1");
$e.attr("id", "id2");
// We force the creation of the property data-gns in the DOM, now it exists (both are different)
$e.prop("data-gns", "springfield");
$e.attr("data-gns", "vans");
// checked is special, because the attribute is deleted from HTML when it's unchecked, the best option is to use always prop
// <input checked> <!-- Checked -->
// <input checked="checked"> <!-- Checked -->
// <input> <!-- Unchecked -->
$e.prop("checked", false);
$e.attr("checked", false);
html_ = html_ + get_html();
$("body").html(html_);<input id="identity" data-gns="brand" checked>