I’m wondering which approach is better and why:
a)
.append('<div class="load" id="XXX"></div>)
b)
.append('<div></div>').addClass('load').attr('id', 'XXX')
c)
your way
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As of jQuery 1.4 you can pass a map object as a second parameter
I find this method much more readable than having a single string or many jQuery method calls and chaining.
Check the docs here. Some issues with IE for input elements.
Anyway both when using jQuery or basic JavaScript, creating an element and its attributes in a string is discouraged. Better to separate the creation and the attribution of the attributes.
I created a fiddle for a direct comparison of the 3 jQuery methods, plus a pure JavaScript one.
While both the new 1.4 option and the usual one are pretty fast, the string method is slow as hell. This is no surprise since jQuery has to parse and interpret it all.
Of course, pure JS is always the fastest option 😉