2

So, I know how to create an element in jQuery in various ways. But I've never come across this before today:

    var myspacer = $('<div />', {
        "id": "nav-spacer",
        "height": mynav.outerHeight()
    });

Later on in the code, this variable is added to the DOM with jQuery's .before() method. Can somebody explain what's going on here? What kind of object is being created? How does jQuery know how to turn this into an HTML element?

SomeKittens
  • 38,868
  • 19
  • 114
  • 143

4 Answers4

5

That is the $( html, props ) syntax of the jQuery() function - it is explained quite clearly in the API documentation:

html A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).

props An map of attributes, events, and methods to call on the newly-created element.

If the function determines that the first parameter is a string that looks like an html snippet it creates a new element (or elements) from that snippet. If you pass a map in the second parameter it creates the specified attributes on the newly created element.

The new element is not automatically added to the document, but you seem to already have seen that since you mention the .before() code that does add it.

Community
  • 1
  • 1
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Thanks, I just found that part of the API right before I came back here to check. Answer accepted (as soon as the time limit goes away) – dabernathy89 Jul 20 '12 at 03:14
  • Note that `$( html, props )` **only** applies to html that matches `(/^<(\w+)\s*\/?>(?:<\/\1>)?$/).` It doesn't apply to `
    ` (Which is a single, standalone, html element -the docs are misleading?), so `$('
    ', {text: "hello"})` will not work (As in, the `text` is not applied). Anything that regex matches will be created using `document.createElement` and the `props` will work on that.
    – Esailija Jul 20 '12 at 09:35
3

According to jQuery $( html, properties) syntax, above code creating a div with id="nav-spacer" and height supplied by mynav.outerHeight() method without any content as jQuery object but not added to DOM.

In $( html, properties), html is string and properties is collection of attributes/event and so on.

An alternative approach may be:

var myspacer = $('<div id="nav-spacer" height="'+ mynav.outerHeight() +'"></div>');

But your one is more readable and efficient.

Using .before() method myspacer is added to DOM just before the selector passed within .before() as param. Example:

myspacer.before('div.hello');

Will add myspacer before the div with class=hello like:

<div id="nav-spacer" height="some_value"></div>
<div class="hello"></div>
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
2

jQuery creates a new element if you pass in HTML like $('<div/>') because it's smart. :P It recognizes that the string is HTML (rather than a selector) and treats it differently. See the docs.

The new element is created but not added to the DOM until you add it yourself, eg. with appendTo().

From the documentation: "To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag."

Edit: I stand corrected, you can write $('<div/>') without an explicit closing tag. This works as long as the HTML doesn't contain nested elements (of course). See the other examples from the docs:

// With nested elements and closing tags - HTML must be well formed
$("<div><p>Hello</p></div>").appendTo("body");

// Without closing tag - HTML is still well formed
$("<div/>", {
  "class": "test",
  text: "Click me!",
  click: function(){
    $(this).toggleClass("test");
  }
}).appendTo("body");

Similar questions:

Community
  • 1
  • 1
Scotty
  • 2,480
  • 2
  • 16
  • 20
  • 1
    @zerkms: You may not need to, but the docs say you should to ensure compatibility. – Scotty Jul 20 '12 at 03:11
  • @Scotty: oh, right, didn't know that and haven't experienced any issues with that – zerkms Jul 20 '12 at 03:13
  • Yeah I wondered about that weird closing on the div. Not my code. – dabernathy89 Jul 20 '12 at 03:15
  • @ahren: The OP doesn't need to know the internals of jQuery ("what kind of object" it is). I don't believe that's what he was actually asking. – Scotty Jul 20 '12 at 03:18
  • "How does jQuery know how to turn this into an HTML element?" - answering this with "because it's smart" isn't answering anything. Also, I do believe he was referring to the `props` object being passed through with the html snippet, rather than the html snippet itself. – ahren Jul 20 '12 at 03:21
  • This is wrong. `
    ` and `
    ` and `
    ` etc are all **exactly** equal to jQuery. They all trigger `document.createElement` from a custom regex jQuery is using (`/^<(\w+)\s*\/?>(?:<\/\1>)?$/`). It has nothing to do with the browser, anything you make that regex succesfully capture will be `.createElement`'d. Your quote is referring to stuff created with `.innerHTML`.
    – Esailija Jul 20 '12 at 09:24
1

http://api.jquery.com/jQuery/#jQuery2

This should give you the explanation you're looking for =D.

To summarize, it's a quick JQuery on-the-fly element creation method.