jQuery: Store and Access the relative information within HTML element

jQuery: Store and Access the relative information within HTML element
jQuery: Store and Access the relative information within HTML element

While making HTML forms or any interactive Web apps, you have faced the requirement to store some more information in elements but not visible to the users.

Here are some methods to Store and Access some related information within the HTML elements.

The old traditional HTML way can be like if you want hidden info in HTML forms you have hidden input fields. But what for a normal page; you can try following things.Actually these are the methods which I was using.

Method 1

You can make an input field of hidden type which has id attribute but no name attribute.

The id will help to access the element and its value by JS and name will help it not to mess with any enclosing form.

And you can access that hidden element and its value in following way by core JS:

<input id="info" type="hidden" value="hello" />
// get the hidden element by its id
var e = document.getElementById('info');

// get the value and use it

And if you know jQuery; you can do it like this


Method 2

Another way is to create any html element with unique id and the value as its text content. And to hide it set its style to display: none or visibility: hidden.

<div id="info">hello</div>

And the access it by either core JS or jQuery:

// vanila JS

// jQuery way

Now here is the third and latest way.

If you people have seen the source code of the websites, you might have noticed some custom attributes like data-value or data-info or something like that.

These custom HTML attributes are things which will let you store additional information with the HTML element without coming in notice of users.

You can create any element with a unique id or use hierarchy of id and classes. This will help you to access these elements very effectively.

Then add some custom attributes to element like data-info etc.

<div id="info" data-info="Hello" data-info2="World!">hello</div>

Here, one thing you have to keep in mind that you have to write data- before your custom information attributes.

Then by jQuery, you can easily access that information in the following way

alert($('#info').data('info')+' '+ $('#info').data('info2') );

And if want to use it in any other way then just by using following code you can obtain all data- attributes as key value pairs i.e. in form of Javascript Object Notation (JSON).

And the data pairs will follow the following type of structure:

You can make the use of above snippets to achieve complex programming tasks like image manipulation, canvas crafting, plugin creation etc.


We saw two methods of storing & accessing some data in the HTML.

Please share your views about your experiences and experiments with this data accessing method of jQuery and this tutorial.

Demo Download

You've successfully subscribed to Time to Hack!