jQuery pitfalls to avoid [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I am starting a project with jQuery.
What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project?

Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-
$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});
Rather than:-
$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});
Or even better with chaining:-
$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});
I found this the enlightening moment when I realized how the call stacks work.
Edit: incorporated suggestions in comments.

Understand how to use context. Normally, a jQuery selector will search the whole doc:
// This will search whole doc for elements with class myClass
$('.myClass');
But you can speed things up by searching within a context:
var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);

Don't use bare class selectors, like this:
$('.button').click(function() { /* do something */ });
This will end up looking at every single element to see if it has a class of "button".
Instead, you can help it out, like:
$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });
I learned this last year from Rebecca Murphy's blog
Update - This answer was given over 2 years ago and is not correct for the current version of jQuery.
One of the comments includes a test to prove this.
There is also an updated version of the test that includes the version of jQuery at the time of this answer.

Try to split out anonymous functions so you can reuse them.
//Avoid
$('#div').click( function(){
//do something
});
//Do do
function divClickFn (){
//do something
}
$('#div').click( divClickFn );

Avoid abusing document ready.
Keep the document ready for initialize code only.
Always extract functions outside of the doc ready so they can be reused.
I have seen hundreds of lines of code inside the doc ready statement. Ugly, unreadable and impossible to maintain.

While using $.ajax function for Ajax requests to server, you should avoid using the complete event to process response data. It will fire whether the request was successful or not.
Rather than complete, use success.
See Ajax Events in the docs.

"Chaining" Animation-events with Callbacks.
Suppose you wanted to animate a paragraph vanishing upon clicking it. You also wanted to remove the element from the DOM afterwards. You may think you can simply chain the methods:
$("p").click(function(e) {
$(this).fadeOut("slow").remove();
});
In this example, .remove() will be called before .fadeOut() has completed, destroying your gradual-fading effect, and simply making the element vanish instantly. Instead, when you want to fire a command only upon finishing the previous, use the callback's:
$("p").click(function(e){
$(this).fadeOut("slow", function(){
$(this).remove();
});
});
The second parameter of .fadeOut() is an anonymous function that will run once the .fadeOut() animation has completed. This makes for a gradual fading, and a subsequent removal of the element.

If you bind() the same event multiple times it will fire multiple times . I usually always go unbind('click').bind('click') just to be safe

Don't abuse plug-ins.
Most of the times you'll only need the library and maybe the user interface. If you keep it simple your code will be maintainable in the long run. Not all plug-ins are supported and maintained, actually most are not. If you can mimic the functionality using core elements I strongly recommend it.
Plug-ins are easy to insert in your code, save you some time, but when you'll need an extra something, it is a bad idea to modify them, as you lose the possible updates. The time you save at the start you'll loose later on changing deprecated plug-ins.
Choose the plug-ins you use wisely.
Apart from library and user interface, I constantly use $.cookie , $.form, $.validate and thickbox. For the rest I mostly develop my own plug-ins.

Pitfall: Using loops instead of selectors.
If you find yourself reaching for the jQuery '.each' method to iterate over DOM elements, ask yourself if can use a selector to get the elements instead.
More information on jQuery selectors:
http://docs.jquery.com/Selectors
Pitfall: NOT using a tool like Firebug
Firebug was practically made for this kind of debugging. If you're going to be mucking about in the DOM with Javascript, you need a good tool like Firebug to give you visibility.
More information on Firebug:
http://getfirebug.com/
Other great ideas are in this episode of the Polymorphic Podcast:
(jQuery Secrets with Dave Ward)
http://polymorphicpodcast.com/shows/jquery/

Misunderstanding of using this identifier in the right context. For instance:
$( "#first_element").click( function( event)
{
$(this).method( ); //referring to first_element
$(".listOfElements").each( function()
{
$(this).someMethod( ); // here 'this' is not referring first_element anymore.
})
});
And here one of the samples how you can solve it:
$( "#first_element").click( function( event)
{
$(this).method( ); //referring to first_element
var $that = this;
$(".listOfElements").each( function()
{
$that.someMethod( ); // here 'that' is referring to first_element still.
})
});

Avoid searching through the entire DOM several times. This is something that really can delay your script.
Bad:
$(".aclass").this();
$(".aclass").that();
...
Good:
$(".aclass").this().that();
Bad:
$("#form .text").this();
$("#form .int").that();
$("#form .choice").method();
Good:
$("#form")
.find(".text").this().end()
.find(".int").that().end()
.find(".choice").method();

Always cache $(this) to a meaningful variable
especially in a .each()
Like this
$(selector).each(function () {
var eachOf_X_loop = $(this);
})

Similar to what Repo Man said, but not quite.
When developing ASP.NET winforms, I often do
$('<%= Label1.ClientID %>');
forgetting the # sign. The correct form is
$('#<%= Label1.ClientID %>');

Events
$("selector").html($("another-selector").html());
doesn't clone any of the events - you have to rebind them all.
As per JP's comment - clone() does rebind the events if you pass true.

Avoid multiple creation of the same jQuery objects
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}

I say this for JavaScript as well, but jQuery, JavaScript should NEVER replace CSS.
Also, make sure the site is usable for someone with JavaScript turned off (not as relevant today as back in the day, but always nice to have a fully usable site).

Making too many DOM manipulations. While the .html(), .append(), .prepend(), etc. methods are great, due to the way browsers render and re-render pages, using them too often will cause slowdowns. It's often better to create the html as a string, and to include it into the DOM once, rather than changing the DOM multiple times.
Instead of:
var $parent = $('#parent');
var iterations = 10;
for (var i = 0; i < iterations; i++){
var $div = $('<div class="foo-' + i + '" />');
$parent.append($div);
}
Try this:
var $parent = $('#parent');
var iterations = 10;
var html = '';
for (var i = 0; i < iterations; i++){
html += '<div class="foo-' + i + '"></div>';
}
$parent.append(html);
Or even this ($wrapper is a newly created element that hasn't been injected to the DOM yet. Appending nodes to this wrapper div does not cause slowdowns, and at the end we append $wrapper to $parent, using only one DOM manipulation):
var $parent = $('#parent');
var $wrapper = $('<div class="wrapper" />');
var iterations = 10;
for (var i = 0; i < iterations; i++){
var $div = $('<div class="foo-' + i + '" />');
$wrapper.append($div);
}
$parent.append($wrapper);

Using ClientID to get the "real" id of the control in ASP.NET projects.
jQuery('#<%=myLabel.ClientID%>');
Also, if you are using jQuery inside SharePoint you must call jQuery.noConflict().

Passing IDs instead of jQuery objects to functions:
myFunc = function(id) { // wrong!
var selector = $("#" + id);
selector.doStuff();
}
myFunc("someId");
Passing a wrapped set is far more flexible:
myFunc = function(elements) {
elements.doStuff();
}
myFunc($("#someId")); // or myFunc($(".someClass")); etc.

Excessive use of chaining.
See this:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
Explanation

Use strings accumulator-style
Using + operator a new string is created in memory and the concatenated value is assigned to it. Only after this the result is assigned to a variable.
To avoid the intermediate variable for concatenation result, you can directly assign the result using += operator.
Slow:
a += 'x' + 'y';
Faster:
a += 'x';
a += 'y';
Primitive operations can be faster than function calls
Consider using alternative primitive operation over function calls in performance critical loops and functions.
Slow:
var min = Math.min(a, b);
arr.push(val);
Faster:
var min = a < b ? a : b;
arr[arr.length] = val;
Read More at JavaScript Performance Best Practices

If you want users to see html entities in their browser, use 'html' instead of 'text' to inject a Unicode string, like:
$('p').html("Your Unicode string")

my two cents)
Usually, working with jquery means you don't have to worry about DOM elements actual all the time. You can write something like this - $('div.mine').addClass('someClass').bind('click', function(){alert('lalala')}) - and this code will execute without throwing any errors.
In some cases this is useful, in some cases - not at all, but it is a fact that jquery tends to be, well, empty-matches-friendly. Yet, replaceWith will throw an error if one tries to use it with an element which doesn't belong to the document. I find it rather counter-intuitive.
Another pitfall is, in my opinion, the order of nodes returned by prevAll() method - $('<div><span class="A"/><span class="B"/><span class="C"/><span class="D"/></div>').find('span:last-child').prevAll(). Not a big deal, actually, but we should keep in mind this fact.

If you plan to Ajax in lots of data, like say, 1500 rows of a table with 20 columns, then don't even think of using jQuery to insert that data into your HTML. Use plain JavaScript. jQuery will be too slow on slower machines.
Also, half the time jQuery will do things that will cause it to be slower, like trying to parse script tags in the incoming HTML, and deal with browser quirks. If you want fast insertion speed, stick with plain JavaScript.

Using jQuery in a small project that can be completed with just a couple of lines of ordinary JavaScript.

Not understanding event binding. JavaScript and jQuery work differently.
By popular demand, an example:
In jQuery:
$("#someLink").click(function(){//do something});
Without jQuery:
<a id="someLink" href="page.html" onClick="SomeClickFunction(this)">Link</a>
<script type="text/javascript">
SomeClickFunction(item){
//do something
}
</script>
Basically the hooks required for JavaScript are no longer necessary. I.e. use inline markup (onClick, etc) because you can simply use the ID's and classes that a developer would normally leverage for CSS purposes.

Related

jQuery methods Vs jQuery selectors

I was recently assigned a very small but complex task in jQuery, the requirement was quite simple, given the following HTML :
<div>
<span id="myid2151511" class="myclass23462362">....foobar....</span>
<span id="myid2151512" class="myclass23462362">....YoLO....</span>
<span id="myid2151513" class="myclass23462362">....lalal....</span>
<span id="myid2151514" class="myclass23462362">....foobar....</span>
</div>
What i have to do i recursively go through all the span under div, With a certain id and check if the values contained in the spans is foobar, So i can up with the following jQuery code:
$(function(){
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' })
});
FIDDLE HERE
Its quite a complex bit of code by itself, but the jQuery documentation made it a cakewalk for me as for as understanding the code is concerned.
By now i am comfortable writing code like so in jQuery:
$('some-Element').somemethod().anothermethod().yetanothermethod();
Every function returns a value in the above jQuery statement, so chain ability becomes a reality.
but when i see code like so.
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' });
I am thrown a bit off the hook(although i managed to write the above line myself), notice how alot of the filtering is done by a selector :last and :contains, to me they appear to be working much like some kind of a jQuery method. So my question is, how do these selectors in jQuery work in comparison to jQuery methods ?
If anybody could explain or give me a vague idea, it would be Fantastic.
EDIT ::
well to clarify my question in one line, to me $(".someClass").eq('10'); makes sense, but somehow $(".someClass:eq(10)") does't , i mean it works, but how on earth is it implemented internally ?(I wrote this edit after reading the answers below, and well this question has been thoroughly answered by now, but this edit is just to clarify my question.).
That's an interesting question. The short answer is they both accomplish the same thing. Of course though, there's always more to the story. In general:
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' });
Is equivalent to:
$("div").find("[id^='myid']").filter(":contains('foobar')").last().css({'background' : 'rgb(227, 216, 22)' });
Most of the time when you call $(), jQuery is calling document.querySelectorAll(). This is a browser implemented function that grabs elements based on a selector. That complex string you create is passed to this method and the elements are returned.
Naturally, things implemented by the browser are faster than JavaScript so the less JavaScript and more C++, the better. As a result, your example passing everything as a selector is likely to be faster as it just sends it all to the browser as one call and tells it "do it." Calling $(), contains(), last() on the other hand is going to call querySelectorAll multiple times and therefore it will likely be slower since we're doing more JavaScript as opposed to letting the browser do the heavy lifting in one shot. There are exceptions though. JQuery generally calls querySelectorAll. However, there are times when it doesn't. This is because jQuery extends what querySelectorAll is capable of.
For example, if you do something like $(".someClass:eq(10)") per the jQuery documentation:
jQuery has extended the CSS3 selectors with the following selectors. Because these selectors are jQuery extension and not part of the CSS specification, queries using them cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using these selectors, first select some elements using a pure CSS selector, then use .filter().
So in that case, while $(".someClass:eq(10)") might seem to be faster, in reality $(".someClass").eq(10) or $(".someClass").filter(":eq(10)") is going to be faster since the first call will be executed as JavaScript code. The latter two will first call querySelectorAll to select by class, then only use JavaScript to find the 10th element. When jQuery has to do the selection in pure JavaScript, it does it using the Sizzle engine which is fast, very fast, but not faster than native code in the browser. So again, the short answer is, they're the same thing, the long answer is, it depends. If you're interested in all the extensions that fall into that category, the link to the jQuery documentation I included lists them.
First of all, yes nikhil was right. ID is unique identifier and can be only used once. If you are willing to apply same styles to several elements, or you to use it to select several elements together use class attribute. But however, i couldn't understand your question. But maybe this could help
there is function in javascript which is widely supported by almost all major browsers
document.querySelectorAll("div [id^=myId]");
in fact you could write your own library (well not as advanced one like jquery but)
var $ = function(selector){
return document.querySelectorAll(selector);
}
// and then you could use it like this
var elementsWithMyId = $("div [id^=myId]");
// where elementsWithMyId will contain array of all divs which's id start with myId
so as i understood your question, No. there is no magic happening behind jQuery selections it's just browser built in function which is kinda shortened by jquery. of course they added tons of new features, which would work like this:
var $ = function(selector){
var elementsArray = document.querySelectorAll(selector);
elementsArray.makeBlue = function(){
for(var i = 0; i < elementsArray.length; i++){
elementsArray[i].style.backgroundColor = "blue";
}
// so elementsArray will now have function to make all of its
// div blues. but if you want to have chain like that, we have to return this array not just make all of it blue
return elementsArray;
}
elementsArray.makeRed = function(){
for(var i = 0; i < elementsArray.length; i++){
elementsArray[i].style.backgroundColor = "red";
}
return elementsArray;
}
return elementsArray;
}
// so now you can use it like this
// this returns array which has options make blue, and make red so lets use make blue first
// makeBlue then returns itself, meaning it returns array which has again options of making itself red and blue so we can use makeRed now
$("div [id^=myId]").makeBlue().makeRed();
and thats it!

How should I use Variables and jQuery Dom navigation?

I was just wondering which is the correct or most efficient way of navigating through the Dom using variables.
For example, can I concatenate selectors
var $container = '.my-container';
$($container).addClass('hidden');
$($container + ' .button').on('click', function(){
//something here
});
or should I use the jQuery traversal functions
var $container = $('.my-container');
$container.addClass('hidden');
$container.children('.button').on('click', function(){
//something here
});
Is there a different approach, is one best, or can you use them at different times?
The $ is usually used only when working with an actual jquery object. You generally shouldn't prefix anything with that unless it's really something from jquery.
Beyond that little bit though, performance-wise, your second bit of code is going to be faster. I made an example jsperf here: http://jsperf.com/test-jquery-select
The reason the second bit of code is faster is because (if I remember correctly) jquery caches the selection, and then any actions performed on that selection are scoped. When you use .find (which is really what you meant in your code, not .children), instead of trying to find elements through the entire document, it only tries to find them within the scope of whatever my-container is.
The time when you wouldn't want to use the second pattern is when you expect the dom to change frequently. Using a previous selection of items, while efficient, is potentially a problem if more buttons are added or removed. Granted, this isn't a problem if you're simply chaining up a few actions on an item, then discarding the selection anyway.
Besides all of that, who really wants to continuously type $(...). It's awkward.

Refactoring jQuery to use $(this) and add/remove classes from another element

so I have this idea I'm working on over on Codepen. I've got it working as it is but before I go and add more clickable areas I've realized a massive need to refactor and DRY things up. So far it works but it's ugly as hell and would involve a massive amount of repeated code.
So I'm trying to replace the many $(.class).click(function() { ... }); functions with a switch statement that uses $(this) to populate a single .click function instead. But I'm lost.
You can see everything here and edit it also: http://codepen.io/lukewatts/pen/ubtmI
I feel like I'm close but I've hit a wall. The top commented out part is the DRY attempt while what is uncommented for now is the working version. Click the min, off, max words or the LEDs to see it work.
Thank you very much in advance for any advise on this. PHP is my main language to be honest.
P.S. I had leds.click(function() { ... }) and I replaced it with leds.on(function() { ... }) but still nothing.
I understand what you are trying to do, but that not how the jQuery object works. In order to check for the object to match a selector, you will have to use .is().
As such, you will not be able to use a switch, but you will have to use a serie of chained ifs to achieve the goal the way you are trying, such as
if ( $this.is('.led[data-level="one"]') )
var led = $('p.min a');
var level = "one";
I have updated your CodePen example to work in this way: Codepen
As I mentioned in my comment to the question, though, I am not making any code review here, just fixing what didn't work for you. I am not sure this is actually a better approach than your messy original one, to be entirely honest.
The refactored version looks good for me. If you don't like to use addClass and removeClass you may directly change the class property of the element:
indicator.attr("class", "one on");
The reason your switch statement doesn't work is because every time you create a jQuery object, it gets an Id, so when the switch tries to compare $this to a selector like $(p.min a), they won't be equal. However, if you used multiple if statements with $.is, you could compare:
$this = $(this)
if($this.is('p.min a')) {
// do work
} else if($this.is('p.max a')) {
// do work
}
I wouldn't, however, recommend this approach. For more complex pages, I'd recommend a binding framework like Knockout.js. For something small, you're adding a lot of complexity. For clarity: If this becomes part of a larger control set or system, a binding framework would be useful. For the control as-is, both a binding framework and the OP's current approach are overkill.
You may want to look at event delegation, I find it very helpful to keeping things DRY. Clicks will bubble up the DOM tree to higher elements, and you can register your handler on an ancestral element. This is actually ideal, as you only bind a single handler to a single element, instead of binding to multiple elements and thus you realize a performance benefit in addition to cleaner code.
First thing, wrap all your .led elements in a <div id="leds">:
<div id="leds">
</div>
Now create your handler:
$('#leds').bind('click', function(e){
var target = e.target;
var $target = $(target);
//do interesting stuff
if (target.nodeName === 'A') {
var level = $target.data('level');
if(level = 'one'){
//do more interesting stuff
}
}
}
});

Is it possible to make this script more efficient?

I have just finished my script, using flot and jquery. Now to my question, it is fast in opera and Firefox, but it is painfully slow in internet explorer (no surprise), so thats why I wonder if there is a way to make my script more efficient (In other words perhaps remove some of the "for loops" etc)? So if there are any code gurus out there who have some spare time to kill, please help me out, because I myself am terrible at writing efficient code :P
Thanks so much in advance =)
It can be found
on this address
A few more tips:
It was pointed out that:
... $(this).attr('id');
... $(this).attr('name');
is expensive, you don't need $ here at all, just use:
... this.id;
... this.name;
Also, using .css(...) is a huge waste, use a class and put the CSS in an style element.
You can store references like $('#x') in closures. Again, you don't need $, it's far more efficient to get a reference directly to the element using document.getElementByid so that rather than:
$('#x').text(pos.x.toFixed(2));
you can have:
x.innerHTML = pos.x.toFixed(2);
which replaces several function calls with a single property access. The basic idea is to remove as much jQuery as you can, keep references to things rather than getting them frequently and use direct property access, not functions.
Incidentally, when I try to copy from the jsFiddle javascript region, Safari freezes. I'm not a big fan of that site.
for(k; k<datasets.length; k++){
Every time the loop is executed next, you are calling the length property, it's better if you store it in a variable at the start of the loop only, like this:
for(var k, len = datasets.length; k < len; k++){
Also here you are wasting resources:
key = $(this).attr("id");
subsystem = $(this).attr("name");
just stich $(this) into a variable, cause every time you use $() a clone of the passed element is created. Just do like this:
var $this = $(this);
And use $this from there on instead of $(this), only reuse $(this) when this become a different object.
Firstly, with jQuery selectors, if using a classname, it's more efficient if you can make that more specific. e.g instead of
var checkboxContainerFailed = $(".failedCheckboxes");
try
var checkboxContainerFailed = $("#graph-table-bottom td.failedCheckboxes");
Secondly, it's generally considered better to use [] notation instead of var subsystemNames = new Array();
Thirdly, you have a trailing comma in the data array here. This might cause IE problems:
"test2-a4/",
]
Finally, try running the whole thing through JSLint for any errors.

What is the most efficient way to create HTML elements using jQuery?

Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
$("<div></div>");
However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?
This answer has the benchmarks to the suggestions below.
I use $(document.createElement('div')); Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.
You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.
personally i'd suggest (for readability):
$('<div>');
some numbers on the suggestions so far (safari 3.2.1 / mac os x):
var it = 50000;
var start = new Date().getTime();
for (i = 0; i < it; ++i) {
// test creation of an element
// see below statements
}
var end = new Date().getTime();
alert( end - start );
var e = $( document.createElement('div') ); // ~300ms
var e = $('<div>'); // ~3100ms
var e = $('<div></div>'); // ~3200ms
var e = $('<div/>'); // ~3500ms
Question:
What is the most efficient way to create HTML elements using jQuery?
Answer:
Since it's about jQuery then I think it's better to use this (clean) approach (you are using)
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'text':'Text Only',
}).on('click', function(){
alert(this.id); // myDiv
}).appendTo('body');
DEMO.
This way, you can even use event handlers for the specific element like
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'style':'cursor:pointer;font-weight:bold;',
'html':'<span>For HTML</span>',
'click':function(){ alert(this.id) },
'mouseenter':function(){ $(this).css('color', 'red'); },
'mouseleave':function(){ $(this).css('color', 'black'); }
}).appendTo('body');
DEMO.
But when you are dealing with lots of dynamic elements, you should avoid adding event handlers in particular element, instead, you should use a delegated event handler, like
$(document).on('click', '.myClass', function(){
alert(this.innerHTML);
});
var i=1;
for(;i<=200;i++){
$('<div/>', {
'class':'myClass',
'html':'<span>Element'+i+'</span>'
}).appendTo('body');
}
DEMO.
So, if you create and append hundreds of elements with same class, i.e. (myClass) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.
Update : Since we can use following approach to create a dynamic element
$('<input/>', {
'type': 'Text',
'value':'Some Text',
'size': '30'
}).appendTo("body");
But the size attribute can't be set using this approach using jQuery-1.8.0 or later and here is an old bug report, look at this example using jQuery-1.7.2 which shows that size attribute is set to 30 using above example but using same approach we can't set size attribute using jQuery-1.8.3, here is a non-working fiddle. So, to set the size attribute, we can use following approach
$('<input/>', {
'type': 'Text',
'value':'Some Text',
attr: { size: "30" }
}).appendTo("body");
Or this one
$('<input/>', {
'type': 'Text',
'value':'Some Text',
prop: { size: "30" }
}).appendTo("body");
We can pass attr/prop as a child object but it works in jQuery-1.8.0 and later versions check this example but it won't work in jQuery-1.7.2 or earlier (not tested in all earlier versions).
BTW, taken from jQuery bug report
There are several solutions. The first is to not use it at all, since
it doesn't save you any space and this improves the clarity of the
code:
They advised to use following approach (works in earlier ones as well, tested in 1.6.4)
$('<input/>')
.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");
So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S) instead of 'size' then it will just work fine, even in version-2.0.2
$('<input>', {
'type' : 'text',
'Size' : '50', // size won't work
'autofocus' : 'true'
}).appendTo('body');
Also read about prop, because there is a difference, Attributes vs. Properties, it varies through versions.
Actually, if you're doing $('<div>'), jQuery will also use document.createElement().
(Just take a look at line 117).
There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.
Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
This is not the correct answer for the question but still I would like to share this...
Using just document.createElement('div') and skipping JQuery will improve the performance a lot when you want to make lot of elements on the fly and append to DOM.
I think you're using the best method, though you could optimize it to:
$("<div/>");
You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.
You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.
Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.
You may be tempted to performance test something like $(document.createElement('div')) vs. $('<div>') and get great performance gains from using $(document.createElement('div')) but that's just an element that isn't in the DOM yet.
However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo();
Let's see, if you test the following against each other:
var e = $(document.createElement('div')).appendTo('#target');
var e = $('<div>').appendTo('#target');
var e = $('<div></div>').appendTo('#target');
var e = $('<div/>').appendTo('#target');
You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.
Test yourself here
So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.
Someone has already made a benchmark:
jQuery document.createElement equivalent?
$(document.createElement('div')) is the big winner.
One point is that it may be easier to do:
$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")
Then to do all of that with jquery calls.
I am using jquery.min v2.0.3 .
It's for me better to use following:
var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);
as following:
var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);
Processing time of first code is much lower than second code.

Categories

Resources