Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html & javascript: How to store data referring to html elements

I'm working on a web application that uses ajax to communicate to the server. My specific situation is the following:

I have a list of users lined out in the html page. On each of these users i can do the following: change their 'status' or 'remove' them from the account.

What's a good practice for storing information in the page about the following:

  • the user id
  • the current status of the user

P.S.: I'm using jQuery.

like image 305
Dan Burzo Avatar asked Jun 01 '09 11:06

Dan Burzo


2 Answers

Perhaps using custom attributes, so for a user's list element, add attributes for the variables:

<li uid="theuserid" ustatus="thestatus"></li>

The values can then be got with the attr function:

$("li").attr("uid")

And

$("li").attr("ustatus")

Note: The selectors will need to be changed, obviously

Please note that there are differing opinions on the use of custom attributes - however, this should be fine for every major browser. It is also the least complex solution I can think of. It doesn't require jumping to sibling elements to get data, or finding elements nearby, which can all add a small amount of overhead to processing - I try to minimise the amount of extra bloat I add to the DOM when doing such things.

like image 80
Alistair Evans Avatar answered Oct 27 '22 15:10

Alistair Evans


There is a lot of debate as to what is best to use. You can store the data a lot of ways, and they all make someone happy - custom attributes will of course not validate if you use XHTML, and using classes to store one or two bits of data is clumsy at best and only gets worse with the amount of things you want to know. Personally, not only am I not a big fan of XHTML, I am also not much of a validation nazi, so I recommend going with the custom attributes.

There is, however, an option that reconciles custom attributes with standards: data- attributes. As John Resig (the author of jQuery) writes about in his blog, this is a new attribute being introduced in HTML5 that allows you to specify custom data attributes with the data- prefix. So a perfectly valid element might look like this:

<ul>
    <li data-userid='5' data-status='active'>Paolo Bergantino</li>
</ul>

This has the upside that while you are still using custom attributes which may be bad if you are using XHTML, your code is going to age very well as this is the way that we will be storing data related to a particular item in the future.

Some further reading is Attributes > Classes: Custom DOM Attributes for Fun and Profit.

like image 40
Paolo Bergantino Avatar answered Oct 27 '22 13:10

Paolo Bergantino