Creating an empty element with start tag vs. self closing tag

前端 未结 3 1713
一整个雨季
一整个雨季 2021-01-11 10:40

In jQuery, is there any difference between this:

$(\'
\').appendTo(\'body\');

And this:

$(\'
\').appe
相关标签:
3条回答
  • 2021-01-11 11:21

    The documentation says:

    When the parameter has a single tag, such as $('<img />') or $('<a></a>'), jQuery creates the element using the native JavaScript createElement() function.

    It also says:

    Tags that cannot contain elements may be quick-closed or not

    So, the form $('<div>') apparently works also, but it's undocumented. It's clear from the documentation that the intention is that a tag that needs a closing tag should either have that closing tag, or be self-closed.

    I would stick to the documented version, as that is less likely to be a victim of a breaking change in a future version.

    <rant>
    The jQuery library have a habit of putting as much as possible in a single function call (see the recent on addition for an example), so it's not so far fetched that they would invent something new to happen when you use a non-self-closing tag...
    </rant>

    0 讨论(0)
  • 2021-01-11 11:24

    That syntax will not cause problems as long as nothing comes after it.

    $("<div>") // Ok!
    $("<div>foobar") // Not Ok!
    $("<div><p>") // Not Ok!
    

    For reference, see http://api.jquery.com/jQuery/#jQuery2

    0 讨论(0)
  • 2021-01-11 11:28

    No. Neither this $("<div>") nor this $("<div />") will cause problems.

    The proof is so that if we go to jQuery sources we can see that in case of selector with single tag syntax <...> it parses selector with this regular expression:

    rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/
    

    where only the symbolic part is used for createElement and closing slash can be optional.

    0 讨论(0)
提交回复
热议问题