When i create the object like on the example A, it won’t apply any attribute (id,class,etc…).
The element is being created but without attributes. Option B works fine, but according to this Spped tests its 25% slower. How to apply attributes using option A? Is it possible after all? Thanks for all smart answers!
A:
var page = $(document.createElement("div"), {
"id": "projects",
"class": "page activePage"
});
B:
var page = document.createElement("div");
page.id = 'projects';
page.className = 'page activePage';
The first option doesn’t make any sense; that’s not how jQuery works (assuming you are using jQuery because of the
$()construction). In jQuery, you’d do it like this:There are other ways to accomplish this via jQuery, but any way you do it would even be slower than option B above, since it’s basically doing the same thing as option B behind the scenes, with a lot of framework around it to slow it down.
Even if the
$refers to a different framework, the same applies — it can’t be faster than the built-in javascript methods.Even more importantly: The speed here is most likely not significant at all. Does this get run thousands of times? If not, no need to care about speed here. And in the rare case it’s significant, you’re not going to get any faster than option B, using just vanilla javascript.