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

10

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

It is reported that the .prop() function came from jQuery 1.6

Did it come to replace .attr() ? Or are both present (and used) in the library today with the same functionality for those who want to use them?

    
asked by anonymous 02.03.2016 / 18:27

2 answers

10

Both have the same functions.

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

An example, more clear and generic, is when you try to access a non-existent attribute in an element, you can access that attribute in the DOM (using .prop() ), however, this attribute is always empty by default. If it is accessed by the .attr() method, it 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><divid="foo">bar</div>

See the result for the console in developer tools. In chrome, press Ctrl + Shift + I and click on the "console" tab.

It will result in this:

   prop retorna vazio: 
   attr retorna indefinido: undefined
    
02.03.2016 / 18:53
6

It depends on the situation, actually the .prop () behind the value, literally and the .attr () content, for example:

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

In the jquery page this is explained in more detail. link

    
02.03.2016 / 18:41