I saw this in some code:
$("<p/>").append("<div>something</div>").appendTo("body");
and noticed that it automatically closed the p
tag in the generated HTML :
<p><div>something</div></p>
I've never seen the selector syntax $("<p/>")
before. Is this mistake (and Chrome is just guessing what it should be) or is this a feature of jQuery's selector syntax?
The $
function is heavily overloaded, even having two functionalities for strings. If the string is a CSS selector, it will return an object containing the matching elements from the document. If you open with <
, it will create the element. jQuery is not creating a tag, however. Elements belong the DOM, tags belong to HTML, which is a serialization of the DOM.
$("<p/>") //Creates a p element
.append("<div>something</div>") //inserts a child element, which is a div you created
//containing the string "something"
.appendTo("body"); //tags the newly created paragraph element, with its div child
//and inserts it into the DOM as a child of the body element.
When you serialize the document, you will wind up with:
<body><p><div>something</div></p></body>
which shows each element containing its children.
If your markup looks like this: <p/><div>something</div>
, then the p
and div
elements are siblings. That would happen if they were appended to the same parent:
//Use add to create a new element and add it to the jQuery collection object
//instead of appending it as a child to the p element.
$("<p/>").add("<div>something</div>").appendTo("body");
it's a feature and jQuery renders the tag correctly.
Feature of jQuery look what happens when you make it a self closing tag by default like link
$("<link/>").append("<div>something</div>").appendTo("body");
It generates
<link><div></div></link>
which is obviously wrong. But that is what it is being asked to do!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With