Benjamin Philip
Benjamin Philip

Reputation: 198

Get instance no of a tag in nokogiri

I would like the to get the instance no. of a tag, i.e - whether a given node is the 1st, 2nd, or 3rd etc. instance of a given tag.

For example, if I call node.path on a node, I get the following output:

/html/head/base/link/body/div/br/form/hr/chapter[1]/section[1]/ul/li[1]/a

How do I get that 1 next to section?

Upvotes: 0

Views: 44

Answers (1)

Chandan
Chandan

Reputation: 11807

require 'nokogiri'

html_string=<<END
<html>
  <body>
    <div>
      <span></span>
      <span></span>
      <span></span>
      <span>
        <h1></h1>
      </span>
      <span></span>
      <span>
        <strong></strong>
      </span>
      <span></span>
      <span></span>
    </div>
  </body>
</html>
END
doc = Nokogiri::HTML(html_string)
h1 = doc.xpath("/html/body/div/span/h1")[0]
puts h1.path         # output => /html/body/div/span[4]/h1
puts h1.parent.xpath("preceding-sibling::*").size + 1         # output => 4

strong = doc.xpath("/html/body/div/span/strong")[0]
puts strong.path     # output => /html/body/div/span[6]/strong
puts strong.parent.xpath("preceding-sibling::*").size + 1     # output => 6

Upvotes: 1

Related Questions