Use Nokogiri to get all nodes in an element that contains a specific attribute name

I would like to use Nokogiri to retrieve all nodes in an element that contains a specific attribute name.

For example, I would like to find 2 nodes that contain the attribute "blah" in the document below.

@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<body>
  <h1 blah="afadf">Three Company</h1>
  <div>A love triangle.</div>
   <b blah="adfadf">test test test</b>
</body>
EOHTML

I found this sentence (below) on this website: http://snippets.dzone.com/posts/show/7994 , but it does not return 2 nodes in the example above. It returns an empty array.

# get elements with attribute:
elements = @doc.xpath("//*[@*[blah]]")

Thoughts on how to do this?

Thank! I found it here.

+3
source share
2 answers
elements = @doc.xpath("//*[@*[blah]]")

XPath. , , "". , XPath .

DZone , ,

elements = @doc.xpath("//*[@*[attribute_name]]")

... , , . .:-p

* , @.

elements = @doc.xpath("//*[@blah]")

, "blah".

+6

CSS:

elements = @doc.css "[blah]"
+3

Source: https://habr.com/ru/post/1763164/


All Articles