Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.prop() versus .data()

Tags:

jquery

With the new release of jQuery v1.6 and the addition of the .prop() method.

Is there an inherent difference in using .prop() over .data() ?

I see in the documentation that not removing a property can result in memory leaks in versions of IE prior to IE9. But are there any other performance issues or other issues with using the new prop() method?

Syntax from the site:

var $para = $("p");    
$para.prop("luggageCode", 1234);

Over the following:

var $para = $("p");
$para.data("luggageCode", 1234);
like image 971
Mike Fielden Avatar asked May 03 '11 17:05

Mike Fielden


3 Answers

I believe prop is intended for setting valid HTML document properties, rather than arbitrary data. I'd suggest you continue to use data for luggageCode type info.

like image 53
Andiih Avatar answered Sep 30 '22 05:09

Andiih


I think it comes down to the difference between a property of the DOM Node, and a property of the Javascript object that represents it.

The documentation does not specify how or where .data() data is stored, so the fact that you're seeing it as a property of the relevant jQuery object may just be an implementation detail. jQuery would be permitted to store it absolutely anywhere else, too.

In contrast, .prop() of course relates explicitly to properties of the DOM Node.

like image 41
Lightness Races in Orbit Avatar answered Sep 30 '22 07:09

Lightness Races in Orbit


I may be going about this wrong, but it seems that .data() can be enumerated, while .prop() cannot.

Live Demo

var $p = $("<p>");
    $p.data('luggagecode', '12345');
    $p.data('luggagecode_backup', '54321');

for (var key in $p.data()) { // generates two alerts
    var value = $p.data(key);
    alert('DATA | '+key+' = '+value);
}

var $p2 = $("<p>");
    $p2.prop('luggagecode', '12345');
    $p2.prop('luggagecode_backup', '54321');

for (var key in $p2.prop()) { // no alerts
    var value = $p2.prop(key);
    alert('PROP | '+key+' = '+value);
}
like image 30
drudge Avatar answered Sep 30 '22 05:09

drudge