jQuery html() and self-closing tags

后端 未结 2 1162
南笙
南笙 2020-12-02 00:16

While creating self-closed elements with jQuery html() the following issue happens:

$(\'#someId\').html(\'
  • 2条回答
    •  长情又很酷
      2020-12-02 00:43

      In the era of HTML5, one might argue that and are equally valid representations of the same void element.

      While that is true, the reason innerHTML still serializes void elements without the /> is twofold:

      • A void element is a void element regardless of how you represent it to the browser. By the time the browser has constructed the element, its markup is irrelevant, and as far as the DOM is concerned, what it is is an input element of type checkbox. The only place the element's "tag" is relevant is its tagName property, and even that has its own quirk.

      • There is no reason whatsoever for a browser to begin serializing a void element with the /> syntax when HTML5 itself, by virtue of being based on HTML, not XML, doesn't require it. Doing so just because it's equally valid to use the /> syntax needlessly breaks compatibility with legacy sites for absolutely zero gain (because the presence of the /> doesn't change the meaning of the output in any way). Which brings us back to cletus's answer distinguishing between HTML markup and XHTML markup.

      innerHTML, and by extension jQuery.html(), was designed to give you an HTML representation of an element's contents from the DOM. It is not designed to give you the HTML markup that the browser used to construct the element in the DOM. You cannot "fix" this because there is nothing to fix to begin with. What you need to do, is avoid relying on an element's innerHTML for anything other than perhaps the occasional debugging session.

      See also: Nested

      tag auto-closing/opening

    提交回复
    热议问题