Which is the correct or better way to create a new element with jQuery?

后端 未结 4 1744
名媛妹妹
名媛妹妹 2021-02-05 19:48

Related to the answer https://stackoverflow.com/a/10619477/1076753 to cleate an element is better to use

$(\"
\", {id: \"foo\", class: \"a\"});
4条回答
  •  半阙折子戏
    2021-02-05 20:24

    From jQuerys website:

    It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler..

    Notice that it doesn't mention HTML generation.

    JavaScript provides the document.createElement method. jQuery utilizes this method if HTML-like string is passed as the selector.

    The jQuery entry point ($(whatEverIFeelLikeDoingToday)) type checks the selector for string, node or function, then handles the request accordingly. If the argument is string, it then passes through +/- 60 lines of code (Am I HTML? Am I a selector, am I an ID, am I a class?). After the HTML-like string is identified, it is then passed to another function (additional function calls) to be generated -therefore slow (see benchmark below). In fact, it doesn't add much value to the process, aside from uniformity, just slows it down.

    I've found the best practice to be: not using jQuery for rather simple tasks (i.e. node creation) -wherever practice, eliminate the obstacles in it's way.

    var div = document.createElement('div');
    div.setAttribute("id", "foo");
    div.setAttribute("class", "a");
    div = $(div);
    

    Notice the significant performance increase in this benchmark. (Just about 4x faster in Chrome). This solution is Faster than the two described above and inherently Cross platform.

    I don't think that the argument for less bytes -vs faster execution time is in the scope of this thread. However, assuming you are minifying your code, I will throw out a the practical example of looping through an array to generate html rows for a table. Bytes aren't the problem, you only needed to load the script once -execution is what bogs you down.

提交回复
热议问题