Skip to main content

Bug Tracker

Side navigation

#12170 closed bug (invalid)

Opened July 31, 2012 09:05PM UTC

Closed July 31, 2012 09:33PM UTC

jQuery selectors do not handle #id correctly in sub-trees

Reported by: andreryan908@gmail.com Owned by: andreryan908@gmail.com
Priority: low Milestone: None
Component: selector Version: 1.7.2
Keywords: Cc:
Blocked by: Blocking:
Description

jQuery does not select the same elements as querySelectorAll when given the same CSS selector string. Specifically, it does not handle the case where the selector contains a #id referring to an element above (or the root of) the sub-tree given as the context parameter of the jQuery search.

var w = document.createElement('div');
var x = document.createElement('div');
var y = document.createElement('div');
var z = document.createElement('div');
var match = x.mozMatchesSelector || x.webkitMatchesSelector || function() { return 'fail'; };

x.id = 'Hello';
x.appendChild(y);
z.className = 'blah';
y.appendChild(z);

console.log($('#Hello .blah', y).length); // prints '0'
console.log(y.querySelectorAll('#Hello .blah').length); // prints '1'
console.log($(z).is('#Hello .blah')); // prints 'true'
console.log(match.call(z, '#Hello .blah')); // prints 'true'

w.appendChild(x);
console.log($('#Hello .blah', x).length); // prints '0'
console.log(x.querySelectorAll('#Hello .blah').length); // prints '1'
console.log($('#Hello .blah', w).length); // prints '1'
console.log(w.querySelectorAll('#Hello .blah').length); // prints '1'

I especially want to emphasise that $(node).is(sel) says the selector DOES match and yet the normal jQuery(sel, node.parentNode) fails to do so.

(Confirmed in Firefox 14 and Chrome 20)

Attachments (0)
Change History (2)

Changed July 31, 2012 09:11PM UTC by timmywil comment:1

component: unfiledselector
owner: → andreryan908@gmail.com
status: newpending

Thanks for taking the time to contribute to the jQuery project! Please provide a complete reduced test case on jsFiddle to help us assess your ticket.

Additionally, be sure to test against the jQuery Edge version to ensure the issue still exists. To get you started, use this boilerplate: http://jsfiddle.net/FrKyN/. Open the link and click to "Fork" (in the top menu) to get started.

Changed July 31, 2012 09:33PM UTC by timmywil comment:2

priority: undecidedlow
resolution: → invalid
status: pendingclosed

Looking closer at your examples, this is intended behavior. See http://ejohn.org/blog/thoughts-on-queryselectorall/ for further explanation.