linodh linodh - 2 days ago 5
HTML Question

Xpath to find all elements following specific node

I have a specific html as shown below and i had observed that there is one specific h2 node that appears in all cases.

<div id='myDiv'>
<..other elements..>
<h2>Locator</h2>
<h3>Header 1 </h3>
<p>Paragraph 1.1</p>
<h3>Header 2 </h3>
<p>Paragraph 2.1</p>
<p>Paragraph 2.2.</p>
<p>Paragraph 2.3.</p>
<h4> test header 4</h4>
</div>


I want all the markups after the specific node the html format is as below.
As you can see i can locate the h2 tag by applying xpath
//div[@id='myDiv']/h2[contains(.,"Locator")]
but the trouble is finding all elements inside the div following the h2 tag.(I am not sure what types of tags can come after this h2 tag).Just to be more clear, What is the xpath to get the following nodes selected

<h3>Header 1 </h3>
<p>Paragraph 1.1</p>
<h3>Header 2 </h3>
<p>Paragraph 2.1</p>
<p>Paragraph 2.2.</p>
<p>Paragraph 2.3.</p>
<h4> test header 4</h4>

Answer

*[preceding-sibling::h2] indicates all elements after h2. So after adding contains in the selector it goes like this

//div[@id='myDiv']/*[preceding-sibling::h2[contains(text(),'Locator')]]

See Demo Here. Click The Test button you will get the result

Comments