Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery automatically closes tags on append? e.g. $("<p/>")

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?

like image 367
Timmy O'Mahony Avatar asked Mar 30 '12 19:03

Timmy O'Mahony


3 Answers

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");
like image 155
Dennis Avatar answered Nov 08 '22 13:11

Dennis


it's a feature and jQuery renders the tag correctly.

like image 44
Daxcode Avatar answered Nov 08 '22 13:11

Daxcode


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!

like image 43
Dave Thomas Avatar answered Nov 08 '22 12:11

Dave Thomas