jQuery HTML strings as selectors


Example

jQuery accepts a wide variety of parameters as "selectors", and one of them is an HTML string. Passing an HTML string to jQuery will cause the underlying array-like structure of the jQuery object to hold the resulting constructed HTML.

jQuery uses regex to determine if the string being passed to the constructor is an HTMLstring, and also that it must start with <. That regex is defined as rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/ (explanation at regex101.com).

The most common use of an HTML string as a selector is when sets of DOM elements need to be created in code only, often this is used by libraries for things like Modal popouts.

For example, a function which returned an anchor tag wrapped in a div as a template

function template(href,text){
    return $("<div><a href='" + href + "'>" + text + "</a></div>");
}

Would return a jQuery object holding

<div>
    <a href="google.com">Google</a>
</div>

if called as template("google.com","Google").