JavaScript AJAX Basics (retiring) AJAX and APIs Stage 4 Challenge Answer

Difference between .prop() and .attr()

Dave in the video uses

$searchField.prop("disabled", true);
  $submitButton.attr("disabled", true).val('searching....)

Why is .prop or .attr not used for both. confused?

2 Answers

Jason Brady
Jason Brady
17,372 Points

I am not completely clear on what Dave did or didn't do, but I can say that referring back to our OOP fundamentals, objects in the DOM tree have properties, and separately, a list of attributes. Properties are defined by the DOM specs, while attributes may differ across browsers, and custom attributes may be assigned. The reason why some may choose to work with attributes is because many properties in the DOM tree get their initial values from attributes, (which may be set in markup, or by script).

Long story short, while they may be somewhat interchangeable, (sometimes) if possible, dealing with the properties of an object will give a more consistent experience than dealing with attributes.

Here is an example of the difference:

var link = document.getElementById('fooAnchor'); alert(link.href); // alerts "http://example.com/foo.html" alert(link.getAttribute("href")); // alerts "foo.html"

A good explanation of this (and the source of my example) can be found at http://stackoverflow.com/questions/5874652/prop-vs-attr