4

How save some data as html tag atribute? For example, given data asd/45.33/blah, I need save this data in html and after using jquery get this data so:

 $("#my_tag").attr("special_attribute");

its possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

7 Answers7

7

Using custom attributes makes your document invalid, you can use HTML5 data-* attributes and for getting/setting values using jQuery, you can use data method, for example if you have a data attribute called data-special you can get the value of it in this way:

var value = $("#my_tag").data("special");

and set/change the value in this way:

$("#my_tag").data("special", "value");

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

Ram
  • 143,282
  • 16
  • 168
  • 197
5

If you need to use it with jQuery then a better way to do it is to use data- attibutes.

Declaring a html tag will look like:

<div id="myDiv" data-url="asd/45.33/blah"></div>

Using data is as simple as:

var url = $('#myDiv').data('url')

More about jQuery data.

Question about attr vs data.

Community
  • 1
  • 1
bumbu
  • 1,297
  • 11
  • 29
0

USE attr() it is used for getting the value as well as for setting the attribute value.

$("#my_tag").attr("special_attribute",'asd/45.33/blah');

Details http://api.jquery.com/attr/

GajendraSinghParihar
  • 9,051
  • 11
  • 36
  • 64
0

Yes it is possible. However it won't validate.

Klevis Miho
  • 851
  • 8
  • 15
  • 7
    It will validate in HTML5 with the data attribute http://www.javascriptkit.com/dhtmltutors/customattributes.shtml – Klevis Miho Dec 27 '12 at 12:23
0

Yes you can. I think you should use an hidden field for this purpose:

<input type="hidden" id="my_tag" />

and then access it via jquery :

$("#my_tag").attr("value", "myvalue");
$("#my_tag").attr("value");
Jerome Cance
  • 8,103
  • 12
  • 53
  • 106
-1

You can save value in html element as :

$("htmlelement").data("key","value");

in your case it would be :

$("#my_tag").data("special_attribute","asd/45.33/blah");
Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35
-3
var html = "<p>HTML</p>";
$("#my_tag").attr("special_attribute", function() {
    return html;
});

Now retrieve it with:

var s = $("#my_tag").attr("special_attribute");
alert(s)
OneMore
  • 1,139
  • 2
  • 9
  • 19
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • 4
    why use function when you can simply assign a variable? – GajendraSinghParihar Dec 27 '12 at 12:23
  • 7
    @AspiringAqib I know a lot of different people have told you already but at SO, we appreciate when there's a meaning behind the code you submit. If you can't answer the "why" question, perhaps it doesn't need to be there. – OneMore Dec 31 '12 at 20:27