XPath: element contains another element

Test Automation engineers that uses XPath for selectors in HTML-tree often face the situation, when they turn to googling. One of such cases is when you are searching for an element that contains another element via XPath.

Let’s imagine that you have such HTML structure:

<!-- 1 -->
<a>
	<b></b>
</a>

<!-- 2 -->
<a>
	<c></c>
</a>

<!-- 3 -->
<a>
	<c>
		<b></b>
	</c>
</a>

<!-- 4 -->
<a>
	<c></c>
	<b></b>
</a>

You need to select all <a> elements that contain element <b> right inside of it.

Your solution is here:

//a[.//b]

It will select cases 1 and 4, because they fulfill the condition when <b> is directly a child of <a>.

 

Leave a Reply

Be the First to Comment!