Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an element in jquery

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?

like image 453
dabernathy89 Avatar asked Jul 04 '26 23:07

dabernathy89


2 Answers

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.

like image 183
nnnnnn Avatar answered Jul 06 '26 14:07

nnnnnn


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>
like image 43
thecodeparadox Avatar answered Jul 06 '26 12:07

thecodeparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!