FrozenHeart FrozenHeart - 1 year ago 90
jQuery Question

How to correctly name programmatically-created tags

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 --
? Or maybe like this --
? Or even like this --

It is unclear for me from the docs.

str str
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download