How to improve this jquery line

2

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());
    
asked by Angelo cardona 19.09.2016 в 21:56
source

3 answers

2

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.

    
answered by 19.09.2016 / 22:50
source
4

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>
    
answered by 19.09.2016 в 22:39
0

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>
    
answered by 19.09.2016 в 22:24