Home > other >  Is there a way to select a specific parent using XPath?
Is there a way to select a specific parent using XPath?

Time:03-04

From the reading I've done so far I don't think it's possible but in the off chance it is, here goes:

Given the following overly simplified HTML (based on HTML generated from a CMS, so no real control over it)

<div >
  <div > <-- This is the one I want
    <div >
      <div >
        <span >
          <input id="experiment-randomnumbers-textinput-2">
        </span>
      </div>
    </div>
  </div>
</div>

I have hacked together the following XPath expression to get the node that I want:

//input[contains(@id,'experiments') and contains(@id,'textinput-2')]/parent::span/parent::div/parent::div/parent::div

The question is, is there a neater way of doing this? I'm assuming it can't be done in CSS?

Cheers

Rob

CodePudding user response:

Let BASE_XPATH = //input[contains(@id,'experiments') and contains(@id,'textinput-2')].

Then, if the target is four ancestors up, and you don't care about the ancestor elements' names:

BASE_XPATH/../../../..

If there's a unique condition (in elided parts of your markup) among ancestors:

BASE_XPATH/ancestor::*[ UNIQUE_PREDICATE ]
  • Related