S S S S - 2 months ago 6
jQuery Question

Get the id of the second element

I have a table structure like this

<tr>
<td>Cover Banner</td>
<td><div id="coverPreview"></div></td>
<td><input type='file' id="coverBanner"/></td>
</tr>


What I am trying to do is when I click on file browse button, I have to get the previous id i.e "coverPreview"

I did like this

$(this).closest('tr').children(':first-child').next().attr("id")


The result I am getting is undefined. Could anyone help me.

Answer

Try getting the closest('td') and using prev() and find() from there. Try this:

var divId = $(this).closest('td').prev().find('div').prop('id');

$('input').change(function() {
  var divId = $(this).closest('td').prev().find('div').prop('id');
  console.log(divId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Cover Banner</td>
    <td>
      <div id="coverPreview"></div>
    </td>
    <td>
      <input type="file" id="coverBanner" />
    </td>
  </tr>
</table>

Comments