I'm writing tests with QUnit and using $.ajax()
to pull in HTML for some of the tests from the the dev site running on my local:
add_elements = function(location, selector) {
$.ajax(location, {async: false}).done(function(data) {
stor.$els = $(selector, $.parseHTML(data));
stor.$els.appendTo($('body'));
})
}
Using this function at a certain location, I get the following data
passed to my .done()
callback:
<!DOCTYPE html>
<html lang=en>
<head>
<title>Home</title>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<link href=/static/css/bootstrap.min.css rel=stylesheet media=screen>
</head>
<body>
<div id=app-container class=container-fluid>
<div class=page-header>
<h1>
<a href=/>Home</a>
<small>Text</small>
</h1>
</div>
<div id=hero-units class=carousel-inner slide>
<div class=hero-unit home item active>
<h1>
Text text text
</h1>
<p>
More text!
</p>
<div id=app-nav>
<a id=lets-go class=btn btn-primary btn-large nav-forward href=/what-up/>
Let's go
</a>
</div>
</div>
</div>
</div>
<script src=/static/js/jquery.js></script>
<script src=/static/js/underscore.js></script>
<script src=/static/js/backbone.js></script>
<script src=/static/js/bootstrap.js></script>
<script src=/static/js/site-fiddle.js></script>
<script src=/static/js/site.js></script>
</body>
</html>
Everything works if selector
is #hero-units
or .hero-unit
, but $(selector, $.parseHTML(data))
returns nothing if selector
is #app-container
! And I want a jQuery
object for the div#app-container
element.
And here is what kills me:
$.parseHTML(data)
does contain thediv#app-container
element. It's just$.parseHTML(data)[7]
.- Yet,
$('#app-container', $.parseHTML(data))
is an empty array. $('div', $.parseHTML(data))
includes all thediv
s inside ofdiv#app-container
, but notdiv#app-container
itself.
What's going on here? It appears that what's happening is that $
is not looking at any of the top-level elements returned by $.parseHTML(data)
or $($.parseHTML(data)))
, and just their children.
How can I get a jQuery
object for div#app-container
from this $.parseHTML(data)
?
ANSWER
The $(selector, $.parseHTML(data))
-style lookup uses $.find
. Since I'm looking for an element that's top-level in this jQuery object, I should use $.filter
instead. Voila.