Reputation: 20746
As well all perfectly know, we can create new elements via the following code:
$('<div/>', {
style: 'display: inline-block;'
})
But I wonder, is there any rules about how they should be created?
Should I pass as the first argument (the tag name) string like this -- <div/>
? Or maybe like this -- <div>
? Or even like this -- div
?
It is unclear for me from the docs.
Upvotes: 0
Views: 66
Reputation: 44969
The documentation is actually quite clear on that. It expects an htmlString
:
A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with ) and is parsed as such until the final > character.
So you cannot use div
as that would actually search for all existing <div>
s in your DOM.
And it also says:
When the parameter has a single tag (with optional closing tag or quick-closing) — $( "
<img />
" ) or $( "<img>
" ), $( "<a></a>
" ) or $( "<a>
" ) — jQuery creates the element using the native JavaScript .createElement() function.
There it clearly says that closing the tag is optional. So either of <div>
or <div />
are fine.
Upvotes: 3