What is the difference between . prop() and . attr()?

Asked

Viewed 9,932 times

12

Do these two jQuery functions do exactly the same thing? Or is there any difference between the same.

You are informed that the function .prop() came from jQuery 1.6

She came to replace .attr() ? Either the two are present (and used) today in the library having the same features for whom you want to use them?

  • 2

    Take a look at these answers in English and you have several examples http://stackoverflow.com/questions/5874652/prop-vs-attr

  • great Gabriel! I’ll see

2 answers

13


Both perform the same functions.

The difference is that the method .prop() is in the DOM and the method .attr() is in the HTML.

An example, clearer and generic, is when you try to access an attribute that does not exist in an element, you can access this attribute in the DOM (using the .prop()), however, this attribute is always empty by default. Accessed by the method .attr(), returns as undefined.

Example:

v = $("#foo").prop("class");
console.debug("prop retorna vazio: "+v);
v = $("#foo").attr("class");
console.debug("attr retorna indefinido: "+v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">bar</div>

See the result for the console in Veloper tools. On Chrome, press Ctrl+Shift+I and click on the "console".

It will result in:

   prop retorna vazio: 
   attr retorna indefinido: undefined

6

Depending on the situation, actually . prop() brings the value, literally and . attr() the content, for example:

 <input type="checkbox" checked="checked"/>
$('input').prop('checked'); //Retorna true
$('input').attr('checked'); //Retorna checked

On the jquery page this is explained in more detail(English). http://api.jquery.com/prop/

  • um... interesting, I just used attr(), did not know what prop() did... You said that depending on the situation, there may be some case where the two will do the same thing?

  • 1

    Actually it’s not that you do the same thing, but the result is the same, when you need the "value" of an element for example...

  • 1

    Great example. The . prop() searches for the DOM, and for the DOM, the checked is a boolean. So it returns true or false. O . attr() goes through the HTML and returns the content, in which case it returns "checked" as a string. Anyway, they do practically the same things with small differences. The biggest difference that is clear is, one acts on DOM and the other on HTML.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.