如何使用CSS选择器部分匹配:not operator

时间:2017-02-12 09:46:38

标签: html ruby css-selectors nokogiri

我想获得不包含特定字符串的Nokogiri元素。

doc = Nokogiri::HTML('<div id="foo"></div><div id="bar"></div>')
doc.css('*[id*="foo"]')
# => <div id="foo"/>
doc.css('*:not[id*="foo"]')
# => []

我认为*:not[id*="foo"]会返回标识为bar的元素,但它不会。

如何同时使用部分匹配和:not运算符?

2 个答案:

答案 0 :(得分:1)

以下是documentation,这里有相应的答案:“CSS use :not ID with CLASS”:

doc.css('div:not(#foo)')

会为您提供id不是foo的所有div。

doc.css('*:not(#foo)')

将为您提供id不是foo的所有节点。

doc.css('div:not([id*="foo"])')

会为您提供id不包含foo的所有div。

require 'nokogiri'
doc = Nokogiri::HTML('<div id="foo"></div><div id="bar"></div><div id="foofoo"></div>')

puts doc.css('div:not([id*="foo"])')
#=> <div id="bar"></div>

答案 1 :(得分:0)

您在负面情况下缺少一些括号。使用:not(whatever)

doc.css('*[id*="foo"]') # All elements with foo contained in the id

doc.css('*:not([id*="foo"])') # All elements without foo contained in the id