Nick Nick - 1 year ago 103
Javascript Question

Element names as constants jquery

Just wondering if anyone has any best practices for naming of jquery elements used in events. e.g elements as constant variables declared at the top, vs inline.

My question for this, is I have a very Jquery heavy client side application and only using server side for data handling and auth.

With this, seeing lines like below drives me a little mad:


Does anyone use any separation such as:

var examplea = "#examplea";
var exampleb = "#exampleb";


I see this looking cleaner in some way, and also means having one place to change code if an element name changed down the track and was used in multiple locations.

I guess this only would become an issue for very large javascript heavy sites, so just throwing out the question on what other people have done to deal with this?


Answer Source

Going to the DOM to fetch the same elements is relatively slow, especially if you get those elements often. It might be better to store the actual jQ variable of it:

var $examplea = $('#examplea');

so that you can use it everywhere else:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download