Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DocumentFragment#search and #at don't handle CSS selectors properly #1205

Closed
epitron opened this issue Dec 7, 2014 · 5 comments
Closed

DocumentFragment#search and #at don't handle CSS selectors properly #1205

epitron opened this issue Dec 7, 2014 · 5 comments

Comments

@epitron
Copy link

epitron commented Dec 7, 2014

Hi there!

I just discovered an odd bit of behaviour for HTML::DocumentFragments. If I try to select elements in the fragment using the #at or #search methods with CSS selectors, no elements are matched. If I use the #css method, however, I do get elements back.

Here's a script to demonstrate the problem:

require 'nokogiri'

puts "Nokogiri version: #{Nokogiri::VERSION}"
puts

a = Nokogiri::HTML.fragment '<em class="testclass">content</em><br /><br /><div id="testid">other content</div>'

puts "The tag: #{a}"
puts
puts "Using at('#testid'): #{a.at("#testid")}"
puts "Using css('#testid'): #{a.css("#testid")}"
puts "Using at('div') #{a.at("div")}"
puts
puts "Using at('.testclass'): #{a.at(".testclass")}"
puts "Using css('.testclass'): #{a.css(".testclass")}"
puts "Using at('em'): #{a.at("em")}"

Note that maching on the tag name does work, for some reason, but classes or IDs don't.

I was expecting the fragments to behave the same as regular Nokogiri documents. Is this a known problem?

Thanks for your time!

@epitron epitron changed the title DocumentFragment#search and #at don't handle CSS properly DocumentFragment#search and #at don't handle CSS selectors properly Dec 7, 2014
@flavorjones
Copy link
Member

@epitron,

Thanks for reporting this. Super interesting! I believe this has to do with how we're handling document fragments, and ignoring root nodes. I'll investigate.

@flavorjones
Copy link
Member

We're missing an specialization of NodeSet#search. Working on it now.

@flavorjones
Copy link
Member

I'd also like to note here that #search is always going to be slower than choosing #xpath or #css, so if you know you have CSS, I'd advise using the appropriate method.

@flavorjones
Copy link
Member

Will be in the next release of Nokogiri, hopefully sometime in the next week or so.

@epitron
Copy link
Author

epitron commented Dec 30, 2014

Awesome! Thanks!

Good to know about that performance trick as well!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants