Click Button

Manuel0815

Newbie
Joined
Jun 12, 2021
Messages
3
Reaction score
1
Hello,

First i want to explain what i want to do.
I have done a website, and in the main part is a section with different Maindivs. Those maindivs have all the same css and html code with a lot of divs in those maindivs. Here for excample:

<section class="_CB11">
<div class="Maindiv>
<div>
<div>
<button></button>
</div>
</div>
</div>
<div class="Maindiv">
same procedure like first Maindiv...
</div>

</section>

My Question:
How can i get the nthChild of the Maindiv when i'm click the button?

And: No i cannot rename every Maindiv to a seperate class or id....
 
This code will get you the parent div.Maindiv to the clicked button.

JavaScript:
function onclick(e) {
  var el = e.target.closest('div.Maindiv');
}
 
Use the element.closest() method like cnick79 suggested to get the surrounding "main" div, then get the Nth child of that by using its children property.

Code:
function onclick(event) {
  var mainDiv = event.target.closest('.Maindiv');

  var firstChild = mainDiv.children[0];
  var secondChild = mainDiv.children[1];
}
 
if you use it for website you can install tampermonkey plugin on chrome ,and install jquery in user script write down code $(".maindiv").eq(1).remove(); fire this function when you click on the button!
 
Back
Top