Reputation: 1503
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.
Upvotes: 2
Views: 437
Reputation: 2678
Try this
$(this).parent().prev().children().attr("id");
Read more about jQuery Traversing
Upvotes: 3
Reputation: 1661
Simple Way
$("this").parent().siblings().find("div").attr("id");
or
$("this").parent().prev().find("div").attr("id");
Upvotes: 1
Reputation: 15555
$('#coverBanner').click(function() {
console.log($(this).parent().prev().find('div').attr("id"))
})
<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>
Use .parent()
, .prev()
and .find()
Upvotes: 1
Reputation: 28741
You have one div in tr so you can search for it using find()
inside parent element.
$(this).closest('tr').find('div').attr('id');
Upvotes: 3
Reputation: 337560
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>
Upvotes: 5