Good afternoon, I have this line of code, it works perfectly, but I would like to know if there is any way to remove all .parent
in some way
$(this).parent().parent().parent().parent().find("input").val($(this).text());
Good afternoon, I have this line of code, it works perfectly, but I would like to know if there is any way to remove all .parent
in some way
$(this).parent().parent().parent().parent().find("input").val($(this).text());
Having ▼:
$(this).parent().parent().parent().parent().find("input").val($(this).text());
An improvement would be ▼:
$(this).parents().eq(3).find("input").val($(this).text());
See .parents()
and .eq()
for more information.
Use closest()
in combination with the type of item or class you want to select. closest
will return the first ancestor element that meets the condition of the selector.
An example of how it works:
$("span").on("click", function() {
$(this).closest("table").find("input").val( $(this).text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div>
<span>Pulsa aquí</span>
</div>
</td>
<td>
<div>
<span>No, mejor aquí</span>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<input type="text" />
</div>
</td>
</tr>
</table>
You can use .parents()
of jQuery.
I'll give you an example
$(document).ready(function(){
$("span").css({"color": "red", "border": "2px solid red"});//elemento this
$("span").parents("ul").css({"color": "red", "border": "2px solid red"});
});
body * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>Elemento this</span>
</li>
</ul>
</div>