How to get the superior parent with JQuery?

2

How can I capture the parent of containers for example I have this structure

<fieldset><!--padre de todos-->
 <div class="on">
<!--some conten-->

</div>

<div class="footer">
<!--con este boton necesito capturar el fieldset-->
 <button>Capturar padre superior</button>
</div>

</fieldset>

I need to make click on the button that is inside the footer capture the father of all, that is the fieldset

example

$("button").click(function(){

    //en esta variable capturaria el padre del botón que es el  div con la clase footer
   var padreSuperior=$(this).parent()
})

How can I access the parent of all by clicking on the button?

    
asked by andy gibbs 29.09.2018 в 21:55
source

2 answers

2

I could use closest ('parameter') to get the first item that matches the specified parameter, it could be an ID , a class or directly a tag like in this case. fieldset

$("button").click(function(){
    //en esta variable capturaria el padre del boton que es el  div con la clase footer
   var padreSuperior=$(this).closest('fieldset');
   console.log(padreSuperior);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset><!--padre de todos-->
	 <div class="on">
	<!--some conten-->

	</div>

	<div class="footer">
	<!--con este boton necesito capturar el fieldset-->
 	<button>Capturar padre superior</button>
</div>
    
answered by 29.09.2018 / 22:52
source
3

For your use case, it would be useful to do:

var padreSuperior=$(this).parent().parent();

But if you're not sure how deep the button can be inside the DOM, you can use closest

var padreSuperior=$(this).closest('fieldsed');

closest can be as specific as you want, if you also give the fieldset a class property.

    
answered by 29.09.2018 в 22:51