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?
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?
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");
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.
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/
Yes it is possible. However it won't validate.
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");
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");
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)