Added CSS :nth() pseudo class

This is a Nokogiri extension (as far as I'm aware) but it's useful
enough to also include in Oga. Selectors such as "foo:nth(2)" are simply
compiled to XPath "descendant::foo[position() = 2]".

Fixes #123
This commit is contained in:
Yorick Peterse 2015-06-29 20:51:38 +02:00
parent 6c8f9704b3
commit 71960fff87
3 changed files with 46 additions and 0 deletions

View File

@ -473,6 +473,16 @@ even
generate_nth_child('following-sibling', arg, current_element)
end
##
# Generates the AST for the `nth` pseudo class.
#
# @param [AST::Node] arg
# @return [AST::Node]
#
def on_pseudo_class_nth(arg)
s(:eq, s(:call, 'position'), arg)
end
##
# Generates the AST for the `:first-child` selector.
#

View File

@ -0,0 +1,21 @@
require 'spec_helper'
describe 'CSS selector evaluation' do
describe ':nth pseudo class' do
before do
@document = parse('<root><a /><a /></root>')
@root = @document.children[0]
@a1 = @root.children[0]
@a2 = @root.children[1]
end
it 'returns a node set containing the first <a> node' do
evaluate_css(@document, 'root a:nth(1)').should == node_set(@a1)
end
it 'returns a node set containing the second <a> node' do
evaluate_css(@document, 'root a:nth(2)').should == node_set(@a2)
end
end
end

View File

@ -0,0 +1,15 @@
require 'spec_helper'
describe Oga::CSS::Parser do
describe ':nth pseudo class' do
it 'parses the :nth(1) pseudo class' do
parse_css(':nth(1)')
.should == parse_xpath('descendant::*[position() = 1]')
end
it 'parses the :nth(2) pseudo class' do
parse_css(':nth(2)')
.should == parse_xpath('descendant::*[position() = 2]')
end
end
end