How to target the parent div from child div?

Using XPath, how can I select a block that contains a specific child element?

  • I have several divs setup with the same class name, 'info'. Each div has an h2 element in it with a unique value. For example, the text of one h2 is 'About'. I want to be able to select the parent div based on the content of its child h2 tag, so that I can then grab the paragraph content within that div. So it's like this div class='info'   h2 about /h2   p content in here /p /div div class='info'   ... I am looking to grab the 'content in here' based on the div having the h2 with 'about' in it.

  • Answer:

    you probably want to use a conditional XPath like so: //div[contains(@class,'info') and p and h2[text()='about']] This will give you: all div elements that have 'info' in their class attribute, have a p element as a child and have an h2 element with text "about" as a child. Note that: this is a pretty basic XPath that does not deal with lower\upper case text, untrimmed text etc. the text must appear as the only child of the h2 element both the p and h2 elements most be direct children of the info div. for more information, you may visit: http://www.w3schools.com/xpath

E-Dan Bloch at Quora Visit the source

Was this solution helpful to you?

Other answers

//h2[contains(., 'about')]/../p

Demitry ҈ ҈ ҈ ҈ Sky

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.