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>');
Related
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.
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.
Do you create it like this: $('<div />') or $('<div></div>')
Is that how you create an element? Thanks.
Either way works just fine. Just don't forget to insert in the dom - you can use appendTo(selector).
var $my_elem = $("<div/>").appendTo(document.body);
var $my_elem = $("<div class='abc'></div>").appendTo(document.body);
Then you have $my_elem represending the inserted element.
Looking at the jQuery source code, it looks like anything matching the regular expression /^<(\w+)\s*\/?>(?:<\/\1>)?$/ will be interpreted as a "single tag" and passed directly to document.createElement (assuming no context is specified). Therefore, at least in the current implementation, there's no difference (behavior or performance) between the various formats.
$('YOUR SELECTOR').append('<div />');
The <div /> will create a <div></div>
You can include classes, id's and other attributes, jQuery should figure it out and rap it up.
I included use of the append function because you are probably going to want to insert it somewhere. There is a number of similar functions you could use instead.
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.
I'm using jquery to parse some HTML, something like:
$(html).contents().each(function(){
var element = this.tagName;
...
I can access the tagName, children, parent... using the DOM or the more friendly jQuery functions.
But at one point a need the whole HTML of the current element (not what innerHTML or .html() return) and I can't figure out a one liner to get it (I always could attach the tag and the attributes manually to the innerHTML).
For example:
Link
The innerHTML is Link but I'm looking for the whole Link
does that oneliner exists?
Looks like this guy has a pretty nifty solution using jQuery: outerHTML
just saw the anwser for this on the other thread :D
outerHTML
outerHTML 2