tmpvar/jsdom — Issue #364: querySelectorAll strange results
Author: jonpacker
Created: 2011-11-15 10:37:51+00:00
State: open

querySelectorAll appears to give unexpected results sometimes when in the context of an element. Given the following test page, both the browser's implementation of querySelectorAll and jQuery within jsdom return the expected result (3), but jsdom's querySelectorAll returns 6 - a NodeList including the elements matching '.subItems li' from the next '.resultItem' down. It occurred to me that the context might just be stuck as the whole document, but the third test disproves that.

**Test Page**

```html

Test page!

testTitle1

testSubItem1

testSubItem2

testSubItem3

seSubTitle1
seSubDetail1

seSubTitle2
seSubDetail2

testTitle2

subTestSubItem1

subTestSubItem2

subTestSubItem3

```

**jsdom Tests**

```coffeescript
jsdom = require 'jsdom'
fs = require 'fs'

page = fs.readFileSync './testpage.html'

jsdom.env
html: page
features:
QuerySelector: true
done: (err, window) ->
firstResultItem = window.document.querySelector "#scopeContainer .resultItem"
firstResultSubItems = firstResultItem.querySelectorAll ".subItems li"

# Gives 6, should give 3
console.log "jsdom querySelectorAll count:", firstResultSubItems.length

jsdom.env
html: page
scripts: ['http://code.jquery.com/jquery-1.5.min.js']
done: (err, window) ->
firstResultItem = window.$ "#scopeContainer .resultItem:first"
firstResultSubItems = firstResultItem.find ".subItems li"

# Gives correct result, 3s
console.log "jQuery .find count:", firstResultSubItems.length

jsdom.env
html: page
features:
QuerySelector: true
done: (err, window) ->
firstResultItem = window.document.querySelector "#scopeContainer .resultItem"
scopeContainer = firstResultItem.querySelectorAll "#scopeContainer"

# correct, is empty nodelist
console.log "jsdom .querySelector out-of-scope:", scopeContainer?.toString()
```

**Browser Test**

```javascript
(function() {
var firstElement = document.querySelector("#scopeContainer .resultItem");
var firstResultSubItems = firstElement.querySelectorAll(".subItems li");
return firstResultSubItems.length;
})();
```

**Result from jsdom**

```
tysfjord:repub jonpacker$ coffee testpage_test.coffee
jsdom querySelectorAll count: 6
jsdom .querySelector out-of-scope: [ jsdom NodeList ]: contains 0 items
jQuery .find count: 3
```

**Result from Browser**

```javascript
// Opera
>>> (function() {
... var firstElement = document.querySelector("#scopeContainer .resultItem");
... var firstResultSubItems = firstElement.querySelectorAll(".subItems li");
... return firstResultSubItems.length;
... })();
3

// Chrome
(function() {
var firstElement = document.querySelector("#scopeContainer .resultItem");
var firstResultSubItems = firstElement.querySelectorAll(".subItems li");
return firstResultSubItems.length;
})();
3
```