creating an element in jquery - javascript

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?

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.

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>

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:
jQuery document.createElement equivalent?
Creating a div element in jQuery
What is the most efficient way to create HTML elements using jQuery?

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.

Related

How to append to a variable in jquery?

I have the following code:
var golden_site = '<div id="golden_site"></div>';
$('.form_content').append(golden_site);
var lookup = '<input type="text" name="lookup" value="test">';
Why is this not working:
$(golden_site).append(lookup);
But accessing the node by id works:
$('#golden_site').append(lookup);
This $('#golden_site') selects the div with id=golden_site. While this $(golden_site) doesn't select anything.
Taken from here, you have the following ways of selecting an element using jQuery
Selecting Elements by ID
Selecting Elements by Class Name
Selecting Elements by Attribute
Selecting Elements by Compound CSS Selector
Pseudo-Selectors
The way you tried to select your div doesn't follow one of the above ways. Hence you didn't make it. While using the id you made it, since this is included in the above ways.
update
As Guffa pointed out (I didn't now it) in his comment,
The call $(golden_site) doesn't try to use the string as a selector at
all. It will create an elements from the HTML string, and actually
return that element
The code is working fine, but it doesn't do what you think.
The $(golden_site) part will create a new div element from the HTML code in the string. The lookup element will then be appended to that div. As the div is an element that you just created, it's not in the page and the lookup element that you appended to it isn't in the page either.
If you create the div element first and then append that to the page, instead of using a string in the append, then you have a reference to the div element:
var golden_site = '<div id="golden_site"></div>';
var element = $(golden_site);
$('.form_content').append(element);
Now you can append things to it:
element.append(lookup);
Because when you say
$(golden_site).append(lookup);
Actually you mean:
'<div id="golden_site"></div>'
In plain words, it's just a string, not a jQuery object that can be appended to. golden_site is just a string.
The reason is because the $() is in fact a wrapper of jQuery over the document.querySelector(). So as expected both methods should behave similar, when you do:
$("#blah").append(x);
Indeed the browser is doing this:
document.querySelector("#blah").appendChild(x);
So both methods should work as they explain here -> How query Selector works
As you can see the variable passed as argument is a string that will be used as a CSS Selector, they explain here -> CSS Selector List
I will add this graphic with some of the most common ways to select elements from the DOM, don't forget the '', courtesy from W3CSchools.

jquery $('<div>') vs $('<div />') [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$('<element>') vs $('<element />') in jQuery
Which one of these two are the correct way to do it:
$('<div>')
or
$('<div />')
They both seem to work. Is one way more right than the other, or do they both always work?
From the docs:
If a string is passed as the parameter to $(), jQuery examines the
string to see if it looks like HTML (i.e., it has <tag ... > somewhere
within the string). If not, the string is interpreted as a selector
expression, as explained above. But if the string appears to be an
HTML snippet, jQuery attempts to create new DOM elements as described
by the HTML. Then a jQuery object is created and returned that refers
to these elements. You can perform any of the usual jQuery methods on
this object:
$('<p id="test">My <em>new</em> text</p>').appendTo('body');
If the
HTML is more complex than a single tag without attributes, as it is in
the above example, the actual creation of the elements is handled by
the browser's innerHTML mechanism. In most cases, jQuery creates a new
element and sets the innerHTML property of the element to the
HTML snippet that was passed in. When the parameter has a single tag,
such as $('<img />') or $('<a></a>'), jQuery creates the element using
the native JavaScript createElement() function.
To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:
$('');
Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):
$('<a/>');
Tags that cannot contain elements may be quick-closed or not:
$('<img />');
$('<input>');
They produce identical results in jQuery.
Though it seems they produce identical result, but based on uses they might not generate same result. For example:
While jQuery parse $('<div> <p>'), the <p> tag will be a children of the<div> tag, so the result would be: <div> <p></p> </div>
And while jQuery parse $('<div/> <p/>'), the <p/> tag will be a sibling of the <div/> tag, so the result would be: <div></div> <p></p>
Both variants give you same result but this
$('<div />', {id:"myID",class:"mycssClass class2 clazzz",some-attribute: "value"});
is better, more readable than
$('<div id="myId" class="mycssClass class2 clazzz" some-attribute="value"></div>');

How to insert created object into a div

I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/
You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div> node as a child of element.
For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click().
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.

Creating DOM elements in jQuery

Let's say we have the following JavaScript/jQuery code below
function createElement(i, value) {
return $('<div>', { id: "field" + i, text: value});
}
I have a div with an id of "container" and then I do:
var c=$("container");
c.append(createElement(1, "hello, world!");
Now I've got 2 questions
Does the createElement function use jQuery to return an HTML string that gets appended to container or does it dynamically create a DOM element that gets appended to the container?
I'm unfamiliar with this kind of jQuery where you actually create the HTML string (or DOM element) via the $() selector. I tried looking for the documentation on this subject in jQuery's website but I couldn't find it. Can somebody point me in the right direction?
It creates the DOM element on the fly, and appends that.
http://api.jquery.com/jQuery/#jQuery2
In fact it creates the DOM element + it returns a jQuery object which contains your DOM element you just created.
Dogbert was right about this, the doc is here

$fn.insertAfter() and $fn.after() Jquery

I understand that $fn.insertAfter() is used to insert element after the element supplied as the argument. How's $fn.after() different from it?
$.fn.after()help inserts an element after the target element, on which you call it.
$('div').after('<div>new div</div>');
whereas, $.fn.insertAfter inserts the target element after the node you specify:
$('<div>new div</div>').insertAfter($('#someid'));
The latter is mostly prefered, because you keep a reference to the newly created element and can chain more methods on it. So for instance:
$('<div>new div</div>')
.insertAfter($('#someid'))
.attr('foo', 'bar')
.css({
'background-color': 'red'
});
is possible. You cannot do that with .after()help. The same thing is for .append()help / .appendTo()help and .insertBefore()help / .before()help
This is an example of the same thing, the difference is the context of the selector. insertAfter inserts the selected element after the parameter
after inserts the parameter after the selected element.
$('<div id="foo"></div>').insertAfter('#bar');
$('#bar').after('<div id="foo"></div>');
Quoting straight from the documentation:
The .after() and .insertAfter()
methods perform the same task. The
major difference is in the
syntax—specifically, in the placement
of the content and target. With
.after(), the selector expression
preceding the method is the container
after which the content is inserted.
With .insertAfter(), on the other
hand, the content precedes the method,
either as a selector expression or as
markup created on the fly, and it is
inserted after the target container.
This mentions that they perform the same task but have different syntax.

Categories

Resources