Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create elements from html returned by .html()?

Tags:

jquery

Has expected, the following jQuery will create nodes from the html :

var nodes = $( "<li>ABC</li><li>DEF</li>" );

Now, consider the following html :

        <ul class="foo">
            <li>ABC</li>
            <li>DEF</li>
        </ul>

My question, why does the following returns an error message instead of the nodes ?

var html = $( "ul.foo" ).html();
var nodes = $( html );

The error message is :

Uncaught Error: Syntax error, unrecognized expression: <li>ABC</li>
            <li>DEF</li> 

You can see it in action here http://jsfiddle.net/HDk47/

like image 740
standac Avatar asked Nov 13 '22 03:11

standac


1 Answers

jQuery's parsing heuristics do not like the leading whitespace in html.

Removing the whitespace fixes the problem:

var html = $.trim( $( "ul.foo" ).html() );

Updated fiddle.

Update: Felix Kling dug up the documentation reference way before I was able to.

like image 126
Jon Avatar answered Nov 15 '22 06:11

Jon