Search code examples
htmlselenium-webdriversvgxpathrelative-locators

Handling Svg element in selenium-java without using index poistion, when all the svg elements have same attribut and values


in my application i'm having 200 svg elements with same attributes and values (//*[name()='svg'][@class='tree-node-icon'])
but when i target one svg element it is located because i used indexed position like this (//*[name()='svg'][@class='tree-node-icon'])[3] (because it has same atribute values for all svg elemnets )
but problem here is when i add new Svg element in UI(i.e Adding folder in our application, it will create new svg element  ) , the selected xpath index value got changed, i mean that position number 3 got changed to 4
how to handle this scenario?

here is Html Dom

<div class="tree-branch" xpath="1">
 <div draggable="false" class="tree-node has-child-nodes">
  <svg width="12" height="12" class="tree-node-icon">
   <path d="M2 1 L10 6 L2 11 Z" class="svg-icon"></path>
  </svg> 
  <span class="tree-node-label">
   <i class="label-icon fas fas fa-folder" aria-hidden="true"></i> 
   <span>Public</span>
  </span>
</div> 

for all the svg element having same html Dom structure , how to handle this without index position

can i locate svg element from

<span>Public</span> to svg

i need to handle the svg element without using index position


Solution

  • This xpath expression locates the shown svg taking the span as predicate

    //*[name()="svg" and following-sibling::span/span[.="Public"]]
    

    Tested on dev console with

    $x('//*[name()="svg" and following-sibling::span/span[.="Public"]]')