For example I have seen things like this:
$('#someElement').css('color','green'); $('#someElement').css('width','200'); $('#someElement').html('Some new text');
The problems with this are:
1) You are selecting the same element three times – this is going to cause additional overhead and potentially performance issues
2) If you want to change the element ID or use a different element then you have to replace all the mentions – in this example this would obviously be trivial – but as your code base grows this is too rigid and inflexible.
4) It makes me sad inside.
A better version would be:
$('#someElement').addClass('myClass').html('Some new text');
Where ‘myClass’ is a defined CSS style. Or if you are using your ‘someElement’ object in many places:
var someElement = $('#someElement'); someElement.addClass('myClass').html('Some new text');
Now someElement can be used throughout your code – without having to go and fetch that bad boy again. As always with stuff like this – do be careful about the scope – consider whether this needs to live in the global space or not depending on what access is required (or consider using namespaces to keep everything tidy).
This is the difference between blindly using things and understanding how they work and using them correctly. Dive in and go and look at the source of jQuery (or your framework of choice) but also, code some stuff up from first principles as well. You’ll learn a hell of a lot and it will help you use the tools that you have available much more effectively.