1
<div class="A">
  <svg> ... </svg>
  <button> 
    <svg> ... </svg>
  </button>
  <svg> ... </svg>
</div>
<div class="A">
  <svg> ... </svg>
  <button> 
    <svg> ... </svg>
  </button>
  <svg> ... </svg>
</div>

I need to retrieve the svg element of button element in the second div. Can someone help me with this?

Jayanth R
  • 11
  • 1

4 Answers4

0

You can use querySelectorAll.

// find all DIVs with class a
const allDivsWithClassA = document.querySelectorAll(".a");
// get the second element
const secondDiv = [...allDivsWithClassA][1];
// find its svg wrapped by button
const svgWrappedByButton = secondDiv.querySelector("button > svg");

console.log(svgWrappedByButton);
<div class="a">
  <svg></svg>
  <button> 
    <svg></svg>
  </button>
  <svg></svg>
</div>
<div class="a">
  <svg></svg>
  <button> 
    <svg></svg>
  </button>
  <svg></svg>
</div>
Matthi
  • 1,073
  • 8
  • 19
  • I agree with your solution for lesser DOM elements. I've just added two divs for reference, there are many numbers of divs in the actual DOM. doing query selector each time would be costly i guess. All i want is, fetch specific instance of div -> button -> SVG. Could be with something like .a:nth-child(2) for the case of the second element. But it is not working (I'm getting Web element found error) – Jayanth R Dec 14 '20 at 17:44
  • @JayanthR I adapted the solution to your needs. So first the second div is being searched for, secondly it is looked for the svg element wrapped by a button. – Matthi Dec 14 '20 at 19:14
0

Try this xpath:

(//div/button)[2]/*[name()='svg']

Note the parentheses usage so you select the 2nd instance of //div/button on the page.

See also this answer: https://stackoverflow.com/a/3371935/1387701

DMart
  • 2,401
  • 1
  • 14
  • 19
0

if you are using xpat hthen you should specify svg as name :

This gives the second element that is a svg element of button and child of div

(//div/button/*[name()='svg'])[2]

if you are using css you can directly use

this finds the div which is second child and then find the svg of button

   div:nth-child(2)>button>svg
PDHide
  • 18,113
  • 2
  • 31
  • 46
-1

First you will have to give an ID to the second div. The styleing will remain the same as you already have it in a class, the Id will make it easier to get the element. Then try this.

function getSVG(){
  // I dont know what Id you'll give it so I named it ParentID
  var parent = document.querySelector("#ParentID");
  var getSvg = parent.querySelectorAll("svg");
  console.log(getDivs);
}