Friday 1 July 2016

javascript - The preferred way of creating a new element with jQuery




I've got 2 ways I can create a

using jQuery.



Either:



var div = $("
");
$("#box").append(div);


Or:




$("#box").append("
");


What are the drawbacks of using second way other than re-usability?


Answer



The first option gives you more flexibilty:



var $div = $("
", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);



And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.



Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery



Placing quotes around the "class" property name will make it more compatible with less flexible browsers.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...