I have below html strcuture:
<div>
<div class="flw__panel__col--12 flw__container__col--12 formSection__col--12">
<div>
<div><div class="EmptyDiv"></div><button onClick={onAddClick} id="RequestNewOrgBtn_prefix-1" class="ui primary button">Request New External Org</button><div></div></div>
</div>
<div>
<div><div class="EmptyDiv"></div><button onClick={onAddClick} id="RequestNewOrgBtn_prefix-2" class="ui primary button">Request New External Org</button><div></div></div>
</div>
</div>
<div class="flw__panel__col--12 flw__container__col--12 formSection__col--12">
<div>
<div><div class="EmptyDiv"></div><button onClick={onAddClick} id="RequestNewOrgBtn_prefix-3" class="ui primary button">Request New External Org</button><div></div></div>
</div>
<div>
<div><div class="EmptyDiv"></div><button onClick={onAddClick} id="RequestNewOrgBtn_prefix-4" class="ui primary button">Request New External Org</button><div></div></div>
</div>
</div>
</div>
when i click on a specific button, it executes below function which gives selected index of all elements in above html that begins "RequestNewOrgBtn", however I want to retrieve the index of the element within div class "flw__panel__col–12 flw__container__col–12 formSection__col–12", but the class isn’t unique, its common. I’m not able to figure it out how do it via parent div since parent div’s class are same?
const onAddClick = (e: any) => {
// find index of selected elememt
let cusid_ele = document.querySelectorAll("[id^=RequestNewOrgBtn]");
const selectedElementId = e.target.id;
for (let i = 0; i < cusid_ele.length; i++){
if( cusid_ele[i].getAttribute("id") === selectedElementId){
setSelectedIndex(i);
}
}
};
2
Answers
Hopefully I understood your question right. It seems like you have 2 divs stored under each class, hence you can assume that the even number is always the latter index, while odd is the preceding one:
you can try the below snippet, it will get all the buttons in the closest parent and give you the indices of those buttons extracting from their ids.