Elaborated the post based on @CBroe flag.
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
<pre><code style="background-color: #f9f2f4;">
$('<ul>').addClass('list').appendTo('body');
// Doesn't do anything
$('<li>').addClass('li1').appendTo('<ul>');
$('<li>').addClass('li1').append('ul');
$('<li>').append('<ul>');
$('<li>').append('ul');
// Working
$('<li>').addClass('li1').appendTo('ul');
$(".list").append("<li>");
</code></pre>
</body>
</html>
If a string is passed as the parameter to $( 'String Vlaue' )
, jQuery examines the provided string in 2 ways.
- HTML snippet.
- Selector expression.
Selector Context: jQuery()
searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements.
var jQuery_object = $( "div.foo" );
Creating New Elements: jQuery examines the string to see if it looks like HTML (i.e., it starts with ). if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. jQuery creates the element using the native JavaScript .createElement()
function.
var html_object = $( "<p id='test'>My <em>new</em> text</p>" );
Create a div element (and all of its contents) dynamically and append
it to the body element. Internally, an element is created and its innerHTML property set to the given markup.
html_object.appendTo( "body" );
@see