ironsand
ironsand

Reputation: 15161

How to use CSS selector partial match with :not operator

I want to get Nokogiri element that doesn't contain a specific string.

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

I thought *:not[id*="foo"] returns the element that has an id bar, but it doesn't.

How can I use partial match and :not operator at the same time?

Upvotes: 0

Views: 1481

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54243

Here's the documentation and here's a corresponding answer: "CSS use :not ID with CLASS" :

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

will give you all the divs whose id isn't foo.

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

will give you all the nodes whose id isn't foo.

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

will give you all the divs whose id doesn't contain foo.

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>

Upvotes: 3

Bustikiller
Bustikiller

Reputation: 2508

You are missing some brackets in the negative condition. Use :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

Upvotes: 1

Related Questions