Javascript – JQuery create HTML object

javascriptjquery

If I look at the JQuery doc @ http://api.jquery.com/jQuery/#jQuery2, it says

…If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML …

However, what if I want this behavior to occur all the time? I'm passing in a variable to $(), and I always want the variable to be interpreted as a HTML, not selector.

One way to do it is wrap the variable with a <span> tag, I don't want to add unnecessary DOM to the tree.

Best Answer

The variable will be interpreted as the value it references. So if your variable contains "<span>", you'll get a span element back.

var tag = "<span>";

var $span = $( tag ); // returns a new span DOM element wrapped in a jQuery object

or if you meant that the variable will only contain the tag name "span", then concatenate the brackets.

var tag = "span";

var $span = $( "<" + tag + ">" );

EDIT: jQuery lets you create DOM elements this way. If you wanted to create something else like a text node, you can use a container as you suggested, but you don't need to add it to the DOM.

var txt = "this will be a text node";

var textNode = $( "<span>", {text: txt} ).contents();

If you append textNode to the DOM, you will only be getting the content of the span.