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?

3
  • 5
    You can use data-* attributes. Commented Dec 27, 2012 at 12:20
  • Did you try it before asking? What happened? Commented Dec 27, 2012 at 12:22
  • 2
    Too much redundancy in the answers Commented Dec 27, 2012 at 12:24

7 Answers 7

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/

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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/

Comments

0

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

1 Comment

It will validate in HTML5 with the data attribute javascriptkit.com/dhtmltutors/customattributes.shtml
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");

Comments

-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");

Comments

-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)

2 Comments

why use function when you can simply assign a variable?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.