jQuery: what is it "forbidden" to do in plain Javascript - javascript

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 checked property 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:
function yourCallback(cb) {
cb = $(cb);
var sel = $(cb).closest('td').next().find('select');
// For example, update the options in a neighboring select field
...
}
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 data function useful to avoid nonstandard DOM attributes. If your property x in your question is in fact a valid DOM attribute, you can write either this.x = y or $(this).attr('x', y), IMO it does not matter much. However, if x is not a DOM attribute, use
$(this).data('key', value)
That way, you can store arbitrary key-value pairs with the DOM element, where value can be an arbitrary primitive value or object.

I think it's a judgement call. Use your common sense.
For instance, if you have 1000 div's on the page, you probably wouldn't want to wrap it inside $(..)
$('div').click(function() {
this.id = Random.guid(); // instead of $(this).attr('id', Random.guid());
});
As for other assignments, as long as you understand what jQuery is doing, you can stick with it just for consistency, but be aware of performance issues like in the above example.
As #colinmarc mentions, at times jQuery blurs the distinction between element attributes and object properties which can be misleading and buggy.

When your using jQuery, it always returns an instance of jQuery unless obv your using a function like val();
the reason we use $(this).value instead of this.value is to make sure that this is an instance of jQuery.
if somewhere in your code you set a variable called my_link witch is equal a DOM Object and not a jQuery function.. further in your application my_link.val() would result into an error, but by doing $(my_link).val() will assure you that the function val will be available. as $() returns an instance of jquery.
Sorry for the miss understanding in my previous post.

Since jQuery objects have richer functionality than nature JS DOM nodes, if you're on the fence, you might as well wrap in jQuery. JQuery is so lightweight, there's not really much reason not to use jQuery objects.
Does it matter if I do this.x=y or $(this).attr("x", y).
The native will be slightly faster, but you'll probably spend more time in other code-- DOM traversal or building. In this specific example, the former is more concise, so I'd choose that. Since jQuery is so lightweight, I tend to switch back and forth fluidly.
Here are other guidelines we follow:
For callbacks, like a click handler, you'll need to follow the API-- usually a DOM node. Code you write that is similar should probably just take DOM nodes as well. But if you have a list of items, always use a jQuery object.
For most code, I try to see if you can structure the code as a jQuery plugin-- applying some transformation to a set of DOM nodes. If you can do that, you'll gain some guidance from the plugin architecture.
I use jQuery's bind/trigger mechanism as it is quite flexible and low-coupling.
To keep code straight, I'd recommend name prefixing jQuery objects with a dollar sign. For example, var $this = $(this);. Although it's really no big deal to call $() excessively, it does end up looking a sloppy if you call it too much.
Hope this helps.

Related

JavaScript variable equals jQuery selector creates open and closing tags. Why?

Please be nice. My first question here. I'm learning JavaScript and jQuery. Google isn't much help because I don't know how to ask the right question. Need human intervention please. I'm trying to figure out what is going on with this simple bit of code:
var myVar = $("<p>");
This creates an opening and closing <p> tag and I don't understand why.
Next, I'll add this paragraph to an existing element #myDiv. For example:
$("myDiv").html(myVar); results in the following:
<div id="myDiv"><p></p></div>
Continuing...
$("myDiv").html(myVar.text("A string for the paragraph"));
Results in:
<div id="myDiv"><p>A string for the paragraph</p></div>
Why does that first snippet create an opening and closing <p> tag? What is this called?
It's simply a more concise method of this in pure JavaScript:
var myVar = document.createElement("p");
And that goes to jQuery like this:
var myVar = $("<p></p>");
And because it's jQuery, and it gets more and more concise, it eventually becomes:
var myVar = $("<p>");
This is the right kind of question to be asking while you learn, so good for you! That being said, one SO post won’t be able to completely answer it, at least in the way that I think you're asking it, but I (we) will give you what I can.
To begin, the way that JavaScript interacts with HTML is through the Document Object Model (DOM). This is like taking an entire HTML document and cutting it up into the individual elements, tags, attributes, etc., and then constructing a representation of that document in "plain" JavaScript as a (very large) Object. The variable name assigned to this Object is document. This special Object has all sorts of magical properties and methods (functions) that can be used to read and update any piece of the DOM (which ultimately translates into the HTML you see in your browser).
What I've described so far has nothing to do with jQuery, and all of that manipulation can be done with plain JavaScript (like Jack Bashford's answer, for example). However, due to the way that browsers and other web technologies have evolved over the years, many "gotchas" exist (or used to exist) when it comes to doing any of this stuff in "plain" JavaScript. jQuery is an incredibly important tool, historically speaking, because it provided a "standard" way to write very direct code to do all of this DOM reading or manipulation, and the jQuery library would make sure that all of the "gotchas" were avoided.
So, what is jQuery (in code, that is)? Well, there could be many technical answers to that, and one important technical answer is that it is an Object, because in JavaScript, (almost) EVERYTHING is an Object. However, let's focus on the question at hand, and the code you provided:
$("<p>");
Here, the dollar sign IS jQuery (or a variable pointing to the jQuery Object). The parentheses that follow indicate that the jQuery Object is being called as a function. It is like saying, in code, "do the jQuery thing with this string of characters: '<p>'." Taking a step back, the full statement
var myVar = $("<p>");
is saying "this variable 'myVar' is now pointing to the results of whatever doing the jQuery thing with '<p>' will give us."
The "magical" thing about writing in jQuery is that the syntax almost always feels the same (and gives it an intuitive feel).
Grab the jQuery Object. This is usually the variable $, but jQuery will also work.
Call the function ($()). There are cases where you don't, like ajax requests, but that's a separate topic and use case.
Supply it with any kind of selector ($('#myDiv')), which is a way of referring to specific HTML elements based on their properties and location in the document (here we are looking up a specific element based on it's id).
Work with the result ($('#myDiv').html(...etc))
I'll point out at this point that the jQuery documentation should be handy so you know what you're getting as a result of any specific function call, but in almost all cases, this function will return another jQuery Object that holds references to whatever elements you selected or manipulated during that function call.
In the latter example, we will receive a reference to the #myDiv element, on which we then call another function (.html()) that will either read or update the contents of that html element.
In the case of the line you specifically asked about, the syntax used to "select" a 'p' tag will be interpreted by jQuery not to look up all 'p' elements in the document (that syntax would be $("p")), but rather to create a single new 'p' element and store it in memory as a jQuery Object that points to this newly created element. Read more about that syntax and its possibilities here.
Well, I hope that was helpful. I sure enjoyed writing it, and even learned a few things along the way myself.

Do jQuery or raw JavaScript precompile or cache variable expressions or selectors?

Pretty basic question.
I want to know if jQuery or raw JavaScript are smart enough to precompile, or cache variable expressions in functions, or selectors, and if not, are there any reasons that would stop them doing this?
e.g.
$('#whatever').on('click', function(){
$('#template').click();
});
var n = 0;
for(var i = 0; i < 20; i++){
n = 1 + 1;
$('#whatever').click();
}
console.log(n);
Are we going to search the dom 20 times for the $('#template') element? or are the library/engine smart enough to store a pointer?
And, are we going to computer 1+1 2 times, or is that expression cached or precompiled?
Obviously these are really dumb examples, but they get the point across.
Yes, no one is going to have the line (hopefully) n = 1 + 1 in their code.
And we could change the code to have `var template = $('#template'); before the click handler if it doesn't deal with it itself, but I am wondering do we/ why we have to do that?
First off, jQuery is javascript. jQuery does not and cannot add features to JavaScript as a language.
With that being said, JavaScript is ECMAScript, and also implemented differently in every browser. It would be very difficult (if not impossible) for me to tell you anything about what level of caching a JavaScript implementation has, because as a language, there isn't any prescribed behavior.
I think it would make sense to cache references to DOM elements for performance reasons, but I cannot speak to what each separate implementation does behind the scenes.
As far as jQuery is concerned, there is no magical selector caching happening in the current version as far as I'm aware. Every time $(...) is called, it has to re-evaluate the selector. The selector could be a simple css-style selector, e.x. $('#foo .bar baz'), or it could be an element fragment, e.x. $('<div>foo bar baz</div>').
If the jQuery function is passed a selector, it would have to re-check the DOM because new elements may have been added that could match the selector, or existing elements may have changed to no longer match the selector.
As far as caching jQuery objects goes, it is common to save a reference to a jQuery object, and in some circumstances is more performant. The only way to know for sure which method is better is to run the script with a performance analyzer and see where the bottlenecks are. There's no reason to just assume that writing your code in one particular way will improve the performance of your code.
If you're just trying to perform a series of operations on the same selection, be sure to take advantage of jQuery's method chaining:
$('.selector').addClass('foo').removeClass('bar').click(function () {...});
jQuery methods typically return the original selection as a return value, which allows for a very elegant simplification of code.

performance issue : storing a reference to DOM element vs using selectors

So in my app, the user can create some content inside certain div tags, and each content, or as I call them "elements" has its own object. Currently I use a function to calculate the original div tag that the element has been placed inside using jquery selectors, but I was wondering in terms of performance, wouldn't it be better to just store a reference to the div tag once the element has been created, instead of calculating it later ?
so right now I use something like this :
$('.div[value='+divID+']')
but instead I can just store the reference inside the element, when im creating the element. Would that be better for performance ?
If you have lots of these bindings it would be a good idea to store references to them. As mentioned in the comments, variable lookups are much much faster than looking things up in the DOM - especially with your current approach. jQuery selectors are slower than the pure DOM alternatives, and that particular selector will be very slow.
Here is a test based on the one by epascarello showing the difference between jQuery, DOM2 methods, and references: http://jsperf.com/test-reference-vs-lookup/2. The variable assignment is super fast as expected. Also, the DOM methods beat jQuery by an equally large margin. Note, that this is with Yahoo's home page as an example.
Another consideration is the size and complexity of the DOM. As this increases, the reference caching method becomes more favourable still.
A local variable will be super fast compared to looking it up each time. Test to prove it.
jQuery is a function that builds and returns an object. That part isn't super expensive but actual DOM lookups do involve a fair bit of work. Overhead isn't that high for a simple query that matches an existing DOM method like getElementById or getElementsByClassName (doesn't in exist in IE8 so it's really slow there) but yes the difference is between work (building an object that wraps a DOM access method) and almost no work (referencing an existing object). Always cache your selector results if you plan on reusing them.
Also, the xpath stuff that you're using can be really expensive in some browsers so yes, I would definitely cache that.
Stuff to watch out for:
Long series of JQ params without IDs
Selector with only a class in IE8 or less (add the tag name e.g. 'div.someClass') for a drastic improvement - IE8 and below has to hit every piece of HTML at the interpreter level rather than using a speedy native method when you only use the class
xpath-style queries (a lot of newer browsers probably handle these okay)
When writing selectors consider how much markup has to be looked at to get to it. If you know you only want divs of a certain class inside a certain ID, do one of these $('#theID div.someClass') rather than just $('div.someClass');
But regardless, just on the principle of work avoidance, cache the value if you're going to use it twice or more. And avoid haranguing the DOM with repeated requests as much as you can.
looking up an element by ID is super fast. i am not 100% sure i understand your other approach, but i doubt it would be any better than a simple lookup of an element by its id, browsers know how to this task best. from what you've explained I can't see how your approach would be any faster.

API design and jQuery [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have often heard that jQuery has made some poor API decisions. Although jQuery is not my favourite library it's the library I've used most often and I find it hard to point out specific mistakes in the API design or how it could have been improved.
What parts of jQuery's API could have been done better, how could it have been implemented different and why would that different implementation be better?
The question extends to both low level individual details of the API and high level details of the API. We are only talking about flaws in the API rather then flaws in the high level design / purpose of the library, jQuery is still a DOM manipulation library centred around a selector engine.
Because of the necessity of API freezing in popular libraries, jQuery is stuck in it's current state and the developers are doing a great job. As can be seen by the recent .attr vs .prop change the developers do not have the flexibility to change any of their design decisions (which is a shame!).
One specific example I can think of would be
$.each(function(key, val) { })
vs
$.grep(function(val, key) { })
which is confusing enough that I have to double check what the parameters are frequently.
Please do not compare the jQuery library to full fledged frameworks like dojo and YUI and complain about lack of features.
.load() is overloaded with entirely different behavior depending on the arguments passed
.toggle() is overloaded with entirely different behavior depending on the arguments passed
too much overloading of the jQuery() function perhaps.
the .attr() you mentioned. The distinction from properties should have been immediate IMO.
.map( key,val ) but $.map( val,key ), and the this values are different.
non-standard selectors ought to have been kept out of Sizzle IMO. Javascript based selector engines should become obsolete in a number of years, and people hooked on the proprietary selectors will have a more difficult transition
poor method naming of methods like .closest() or .live(). What exactly do they do?
I recently discovered that you can't set the standard width and height attributes via the props argument when creating a new element. jQuery runs its own width and height methods instead. IMO, the spec attributes should have been given priority, especially since width and height can be set via css.
$('<img/>', {
css:{width:100, height:100},
width:100, // <-- calls method, why?
height:100, // <-- calls method, why?
});
$.get() and .get() are entirely different.
.get() and .toArray() are identical when passing no arguments
toArray() and $.makeArray() do effectively the same thing. Why didn't they give them the same name like .each() and $.each()?
two different event delegation methods. .delegate() the sensible one, and .live() the magical "wow, it just works!" one.
.index() is overloaded with 3 behaviors, but their differences can be confusing
// v---get index v---from collection (siblings is implied)
$('selector').index();
// v---from collection v---get index
$('selector').index(element);
// v---get index v---from collection
$('selector').index('selector');
The first one is understandable if you remember that it only operates on the first element
The second one makes the most sense since jQuery methods usually operate on an entire collection.
The third one is entirely confusing. The method gives no indication of which selector is the collection and which selector represents the element whose index you want from the collection.
Why not just eliminate the third one, and have people use the second one like this:
// v---from collection v---get index
$('selector').index( $('selector') );
This way it fits more closely with the rest of jQuery where .index() operates on the entire collection.
Or at least reverse the meaning of the selectors to fit in better:
// v---from collection v---get index
$('selector').index('selector');
Here's another to think about anyway.
I have some concerns with jQuery's event handling/data storage system. It is praised because it doesn't add functions to on[event] properties that can close around other elements, creating memory leaks in IE. Instead it places a lightweight expando property, which maps to an entry in jQuery.cache, which holds handlers and other data.
I believe it then attaches a handler with in turn invokes the handler that you assigned. Or something like that.
Whatever the system is doesn't really matter. The point is that the connection between the element(s) and the jQuery.cache is that expando.
Why is that a big deal? Well philosophically jQuery is not a framework; it is a library. It would seem that as a library you should be able to use or not use the jQuery functions without concern for negative effects. Yet if you go outside jQuery when removing elements from the DOM, you've orphaned any handlers and other data associated with those elements via the expando, creating a nice and fully cross-browser memory leak.
So for example, something as simple as el.innerHTML = '' could be very dangerous.
Couple this with the jQuery.noConflict() feature. This enables developers to use jQuery with other libraries that utilize the $ global namespace. Well what if one of those libraries deletes some elements? Same problem. I have a feeling that the developer that needs to use a library like Prototypejs along side jQuery probably doesn't know enough JavaScript to make good design decisions, and will be subject to such a problem as I've described.
In terms of improvements within the intended philosophy of the library, as far as I know, their philosophy is "Do more, write less" or something. I think they accomplish that very well. You can write some very concise yet expressive code that will do an enormous amount of work.
While this is very good, in a way I think of it as something of a negative. You can do so much, so easily, it is very easy for beginners to write some very bad code. It would be good I think if there was a "developer build" that logged warnings of misuse of the library.
A common example is running a selector in a loop. DOM selection is very easy to do, that it seems like you can just run a selector every time you need an element, even if you just ran that selector. An improvement I think would be for the jQuery() function to log repeated uses of a selector, and give a console note that a selector can be cached.
Because jQuery is so dominant, I think it would be good if they not only made it easy to be a JavaScript/DOM programmer, but also helped you be a better one.
The way jQuery handles collections vs single elements can be confusing.
Say if we were to update some css property on a collection of elements, we could write,
$('p').css('background-color', 'blue');
The setter will update the background color of all matching elements. The getter, however, assumes that you are only interested in retrieving the value of the first element.
$('p').css('background-color')
MooTools would return an array containing the background colors of each matching element, which seems more intuitive.
The naming conventions for jQuery promote conciseness instead of clarity. I like Apple's strategy in naming things:
It's better to be clear than brief.
And here's an example of a method name from a mutable array class (NSMutableArray) in Objective-C.
removeObjectAtIndex:(..)
It's not trying to be clever about what's getting removed or where it's getting removed from. All the information you need to know is contained in the name of the method. Contrast this with most of jQuery's methods like after and insertAfter.
If somebody can intuitively figure out what after or insertAfter does without reading the docs or the source code, then that person is a genius. Unfortunately, I'm not one - and to-date, I still have to go to the documentation to figure out what the hell gets placed where when using these two methods.
patrick dw hit most of the points in his (fantastic) answer. Just to add to his collection with a few other examples.
An API is supposed to be consistent; and jQuery succeeds in a lot of areas (being very consistent for returning a jQuery object/ get value, as expected in a lot of cases). In other situations however, it doesn't do so well.
Method Names
As already pointed out by patrick; closest() is a crap method name. prev(), and next() appear to most as if they do the job prevAll() and nextAll() actually provide.
delay() confuses a lot of people: In the following example, which do you expect to happen? (what actually happens?)
$('#foo').hide().delay(2000).slideDown().text('Hello!').delay(2000).hide();
Method Arguments
A lot of the tree traversal functions are inconsistent with what they accept; they all accept a mixture of selectors, jQuery objects and elements, but none are consistent; which is bad considering they all do similar jobs. Check out closest(), find(), siblings(), parents(), parent() and compare the differences!
Internally, the "core" of jQuery originally contained lots of intertwined methods, that the dev team have struggled to split up (and done really well to), over the past releases. Internal modules such as css, attributes, manipulation and traversing all used to be bundled in the same big package.
Included in jquery:
.post()
.get()
.getScript()
.getJSON()
.load()
Not in jQuery:
$.getXML();
$.headXML();
$.postXML();
$.putXML();
$.traceXML();
$.deleteXML();
$.connectXML();
$.getJSON();
$.headJSON();
$.postJSON();
$.putJSON();
$.traceJSON();
$.deleteJSON();
$.connectJSON();
$.headScript();
$.postScript();
$.putScript();
$.traceScript();
$.deleteScript();
$.connectScript();
$.getHTML();
$.headHTML();
$.postHTML();
$.putHTML();
$.traceHTML();
$.deleteHTML();
$.connectHTML();
$.getText();
$.headText();
$.postText();
$.putText();
$.traceText();
$.deleteText();
$.connectText();
$.head();
$.put();
$.trace();
$.delete();
$.connect();
Why does this bother me? Not because we don't have the above methods in the library, that's just dumb and I'd hate if we ever did (plus, most won't work with browsers), but what I hate is these short-hand methods all over the place: $.post(); Sends an ajax request via post.
Know what covers off everything in this list? The one function that isn't short-hand, $.ajax, it's full featured and covers off everything, you can even configure it to store defaults and in essence create all of these short-hands. You can create your own methods if you wish to call that call to ajax (which is what these all do).
Here's where it's really REALLY annoying.
Somebody writes all their code using shorthand:
$.getJSON(
'ajax/test.html',
function(data) {
$('.result').html(data);
}
);
Okay, oh wait, we want to change that to an XML feed we get from a post, also we need to make something happen before and after post. Oh, lets just switch to the non-short-hand method
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
Oh wait, I can't just replace the word, the whole structure is all over the place.
This, and especially for things like $.load(), cross lines into why PHP has such a hated API, they're trying to do things they shouldn't do.
To extend this beyond AJAX calls, look at the animation portion. We have calls to slideUp, slideDown, fadeIn, fadeOut, fadeToggle, show, and hide. Why? Where's my slide left, slide right, slide in, slide out, teleport, and every other thing we can think up? Why not just stick to $.animate() and let someone write a plugin if we want those effects. Infact, someone did write a plugin, jQueryUI extends animations. This is just crazy, and leads to people not knowing that some effects create CSS rules on their divs that end up goofing up what they want to do later on.
Keep it pure, keep it simple.

DOM properties/methods that aren't available in jQuery?

Following up on my question about jQuery.get() I was wondering if there is a list of DOM properties and methods that aren't available in jQuery that can only be accessible if you were working with the raw DOM object (i.e. $("#someID").get().scrollHeight; )
I haven't encountered a list but if one existed it would probably be quite lengthy. In addition to browser-specific (proprietary) properties there's a bunch of other less useful properties and methods not currently abstracted by jQuery. But then, I don't really see this as a problem, or even a valid point of discussion because jQuery IS JavaScript; if you need access to something beyond what jQuery provides then you can use get() or access a specified element within one of your "jQuery collections" like an array:
jQuery(elem)[0].someDOMProperty;
Plus jQuery provides absolutely no support for non-element nodes within the DOM. If, for whatever reason, you need direct access to comment nodes, text nodes etc. then you'll need to use the "raw" DOM.
I don't know of a compiled list of DOM operations/properties that are NOT available in jQuery (and a quick google search didn't turn anything up), but if you go to http://api.jquery.com/ you can see the entire API, and even download it as an Adobe AIR app in case you don't have internet when you need it.
No. JQuery is just JavaScript. If you can do it in JavaScript, you can do it in jQuery. Some properties and methods are overwritten in the context of a jQuery object and that's where you would want to us the get() method--to 'get' (i.e. access) the standard property/method.
That's really as complicated as it is.
Every attribute of every element is accessible through the attr() function. If you could do a document.getElementById() on that element and then access a property, you can also do it using the attr() function. However, some properties are accessed more easily in other ways when using jquery. For example, to see if an element is hidden or visible, you could do:
var isVisible=$("#el").is(":visible");
instead of using the attr() method. Similarly, you can find the selectedIndex of dropdowns and the text of the selected option, in easier ways than using the attr() method. This pdf outlines some of these easier approaches.
To access a css property, you are better off doing:
var fontWeight=$("#el").css("fontWeight");
rather than using get() or attr(). You can also set the css properties in this way, e.g:
$("#el").css("fontWeight","bold");
I could be wrong, but I think you can access any properties via the attr method.

Categories