A jQuery best practices question.
I am writing a very jQuery intensive web page. I am new to jQuery and notice its power, but as I come with heavy javascript experience and knowledge, my question is: What should be done in jQuery and what in plain javascript.
For example, there are callbacks that send a plain DOM object as an argument. Should I use that or should I wrap it ( like $(this)).
Does it matter if I do this.x=y or $(this).attr(“x”, y).
If your function receives a DOM object and you don’t need any jQuery functionality for that DOM object, then there is no need to make convert it to a jQuery object. For instance, if you receive a checkbox object, you can examine the
checkedproperty without any use of jQuery.However, if you need to navigate to a different element from that checkbox, it might be worthwhile to convert it:
jQuery (as do other libraries) blend in smoothly with native JS. If you need extra functionality, augment the object in question.
As for your last question: You might find the
datafunction useful to avoid nonstandard DOM attributes. If your propertyxin your question is in fact a valid DOM attribute, you can write eitherthis.x = yor$(this).attr('x', y), IMO it does not matter much. However, ifxis not a DOM attribute, useThat way, you can store arbitrary key-value pairs with the DOM element, where
valuecan be an arbitrary primitive value or object.