Attributes v. Properties

by Greg Milby

HTML

<p>Open the console, click these, and note that the attribute's don't change.  Attributes and properties are not the same.</p>

<input type="checkbox" id="checked" checked="checked">
<input type="checkbox" id="none">

JavaScript

// Attributes and properties are different.
// An attribute is set from the HTML tag.
// A property is the state of the DOM element.
// Elements and tags are not the same thing.

// So <input type="checkbox" checked="checked"> has the attribute "checked" set
// to "checked", and therefore the property checked is true also. But when the
// user clicks the checkbox the checked property is now false but that doesn't
// change the "checked" attribute of the tag.

// It gets confusing because setting the html "checked" attribute also sets the
// checked property, but setting the propery (like a user clicking) does NOT
// set the attribute.  One way street.

var $checked = jQuery('#checked'),
    $none = jQuery('#none');

console.log(
    'attr:', $checked.attr('checked'),
    'prop:', $checked.prop('checked')
);

console.log(
    'attr:', $none.attr('checked'),
    'prop:', $none.prop('checked')
);

jQuery('input').bind('click', function () {
    $input = $(this);
    console.log(
        'attr:', $input.attr('checked'),
        'prop:', $input.prop('checked')
    );
});