Skip to content

Instantly share code, notes, and snippets.

@wolframarnold
Created January 8, 2011 14:38
Show Gist options
  • Save wolframarnold/770885 to your computer and use it in GitHub Desktop.
Save wolframarnold/770885 to your computer and use it in GitHub Desktop.
Illustration of Nokogiri 1.5.0.beta3 bug with first-of-type and nth-of-type pseudo selectors
html = %Q{
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="/">
<p>First child</p>
<div class="doc_form">
first doc form, should be blue
</div>
<div class="doc_form">
second doc form, should be green
</div>
</form>
</body>
<!- This is for verifying that the browser's CSS parser interprets first-of-type correctly ->
<style>
form .doc_form:first-of-type {
color:blue;
}
form .doc_form:last-of-type {
color:green;
}
</style>
</html>
}
require 'rubygems'
require 'nokogiri'
# To check browser CSS rules, load this file into a browser
File.new("css-first-of-type-example.html", 'w') { |f| f << html }
doc = Nokogiri::HTML.parse(html)
# first-of-type produces an empty array, but shouldn't
puts "CSS rule: 'form .doc_form:first-of-type' should not be empty but returns: '#{doc.css('form .doc_form:first-of-type').inspect}'"
# nth-of-type(1) produces an empty array, but shouldn't
puts "CSS rule: 'form .doc_form:nth-of-type(1)' should not be empty but returns: '#{doc.css('form .doc_form:nth-of-type(1)').inspect}'"
# nth-of-type(2) produces the first entry, but should be the 2nd -- counting is off
puts "CSS rule: 'form .doc_form:nth-of-type(2)' should have content 'second doc form...' but return: '#{doc.css('form .doc_form:nth-of-type(2)').text}'"
# nth-of-type(3) produces the second entry, but should be the 3rd -- counting is off
puts "CSS rule: 'form .doc_form:nth-of-type(3)' should not have content, but returns: '#{doc.css('form .doc_form:nth-of-type(3)').text}'"
# last-of-type works correctly
puts "CSS rule: 'form .doc_form:last-of-type' should have content 'second doc form, should be green' and returns: #{doc.css('form .doc_form:last-of-type').text}"
@wolframarnold
Copy link
Author

wolframarnold commented Jul 24, 2011 via email

@n00ge
Copy link

n00ge commented Jan 22, 2013

I just hung up on this. I'm using 1.1.2. Is this fixed in 2.0?

@stanmx
Copy link

stanmx commented Aug 3, 2013

I'm using 1.6.0 rc1, is this bug fixed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment