<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?
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>
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
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
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); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.