1

What is better?

var itemId=8;
$('#aaa').data('ItemId', itemId);
$('#aaa').attr('ItemId', itemId);

data or attr?

Naor
  • 23,465
  • 48
  • 152
  • 268

1 Answers1

6

They serve different purposes.

  • If you want to store general data associated with an element, use .data().
  • If you want to change the attributes of the DOM element, use .attr().

Don't "invent" new attributes (appart from HTML5 data attributes). But as you are using jQuery, stick with .data().

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I can add attribute: $('a').attr('blabla',7); is like – Naor Jan 05 '11 at 20:56
  • @Naor: I know you can, but you should not do it. – Felix Kling Jan 05 '11 at 20:57
  • Why? Isn't data more slower then attr? – Naor Jan 05 '11 at 20:59
  • @Naor: It is not about speed. It is about correctness. If you add custom attributes to the DOM element, then you are creating invalid HTML (theoretically). DOM attributes are not for storing arbitrary data. Every type of element has a well defined set of attributes and you should not add custom ones.`data()` is for associating arbitrary data with an element. – Felix Kling Jan 05 '11 at 21:01
  • Why can't I use attr? creating invalid html is not the issue. JQuery itself adds attributes to elements.. – Naor Jan 05 '11 at 21:06
  • 1
    @Naor: I already told your: *you should not add custom attributes* because DOM elements have a well defined set of attributes (your document is not valid anymore if you add custom ones). Only because it is possible does not mean it is a good idea. Maybe you want to read this: http://stackoverflow.com/questions/1735230/can-i-add-custom-attribute-to-html-tag – Felix Kling Jan 05 '11 at 21:09
  • @Felix Kling: Why JQuery add attributes to elemnts? Does it OK? – Naor Jan 05 '11 at 21:27
  • @Naor does JQuery add attributes that aren't real attributes? If it's a real attribute then use `attr`, otherwise use `data`. Like @Felix said it's about doing the "right" thing. Would you steal if no one's looking and there's no cameras? Just because you probably won't get in trouble for misusing it doesn't mean you should. Likewise just because someone else does, it doesn't mean you should. – Davy8 Jan 05 '11 at 22:16