Tim Joyce
Tim Joyce

Reputation: 4517

Custom HTML attributes and jQuery

I am often needing to store little pieces of reference in a page element, most of the time a <div>. I couldn't find too much documentation on how valid it would be to create my own attributes. What do you suggest is the most valid way of doing this or can I even do this? If so, can I just use jQuery's attr() call to get the reference?

example : <div class="sample" dataref="Sample Data Reference"></div>

Upvotes: 11

Views: 19560

Answers (3)

manny
manny

Reputation: 1948

I feel you can use any word other than "id" and "class" attributes to keep your data.

Upvotes: 0

mateusz.fiolka
mateusz.fiolka

Reputation: 3100

Use jQuery data functionality. The data will not show in DOM, but you will able to set and access it fast. Documentation:

http://api.jquery.com/jQuery.data/

Example:

// set value
$.data(element, key, value);

// get value
var value = $.data(element, key); 

Upvotes: 1

Petah
Petah

Reputation: 46050

Use HTML5 data attributes

See: http://api.jquery.com/data/

E.g.

<div class="sample" data-ref="some string" />

Then:

$('.sample').data('ref');

Upvotes: 30

Related Questions