jQuery selector not behaving as expected in parsed HTML from ajax

Viewed 379

I've ran into a weird issue today, I'm hoping someone else can help me figure this out.

The project that I'm working on is more-or-less a jQuery slideshow. I have a super simple file that I'm loading to test everything out, it looks something like this:

<!doctype html public "(╯°□°)╯︵ ┻━┻">
    <html>
        <head>
            <meta charset="utf-8">
            <title>test</title>
        </head>
        <body>
            <div id="slides" data-slidesShow="holder">
                <div class="slide" id="test1">test div 1</div>
                <div class="slide" id="test2">test div 2</div>
                <div class="slide" id="test3">test div 3</div>
            </div>

            <button id="previous">previous</button>
            <button id="next">next</button>

            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
            <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>

            <script type="text/javascript" src="js/slides.js"></script>

            <?php include 'footer.php'; ?>
        </body>
    </html>

Again, nothing even remotely fancy here.

Now, in jQuery I'm getting and parsing the page like:

$.ajax({
    url:      target.path,
    dataType: "html",
    complete: function(data){
        var $slides     =   $('[data-slidesShow="holder"]', $(data.responseText));

        console.log($slides); // returns []
    }
});

BUT! $slides returns an empty array, unless I wrap it in a meaningless div, like:

<div class="stupid-wraper-div-that-i-dont-want-or-need">
    <div id="slides" data-slidesShow="holder">
        <div class="slide" id="test1">test div 1</div>
        <div class="slide" id="test2">test div 2</div>
        <div class="slide" id="test3">test div 3</div>
    </div>
</div>

and now:

console.log($slides); // returns [<div id="slides" data-slideShow="holder">...</div>]

I've read over the jQuery docs on this (http://api.jquery.com/jQuery/) and other StackOverflow conversations, but none of them explain why I would need a wrapper div to have results returned.

Any ideas? I know it's not a huge issue, but I don't want to have to hack a fix when I could find the root of the problem.

...

TL;DR: jQuery's select in scope only works with a weird wrapper div

2 Answers
Related