Search code examples
htmldomxpathgoogle-chrome-extension

Find Element with Text, then Select Element Many Levels Above it


I am making a chrome extension that deletes a section of a website. To do this, I need to find a <span> that contains some text, and then select the containing <div> tag. Often this tag will be many levels above the span in the DOM, and it doesn't have a consistent attribute to select by.

HTML

<body>
  <div> <!-- I want to select this DIV -->
    <div>
        <div>
            <div>
                <span>some text</span>
             </div>
         </div>
    </div>
  </div>
</body>

I have used //span[text() = 'some text' to find the right <span> but now I need to go back up to the first <div> in the example HTML

Have tried //*[ancestor::span[text() = 'some text']] and //span[ancestor::*[text() = 'some text']]. Yes these would only go up to the first parent, but that's not even working for me, even though they come up as valid XPath expressions when I test on XPath Tester.

What is the simplest way of writing an XPath expression that can do this?


Solution

  • A better solution I have found is to use ancestor in the XPath query, because I am often wanting to traverse up many levels.

    Examples

    //span[text() = 'some text']/ancestor::*[4]
    

    selects the fourth element up from the selected span, regardless of what type those elements might be.

    //span[text() = 'some text']/ancestor::a[2]
    

    Will find the second anchor tag up from the selected span, provided it is a direct ascendant of the span.