How to find the closest sibling in jQuery
When i click the edit button, i want to get the date and description of that div
You can use .siblings()
to select .date
, .desc
siblings of .edit
element
$(document).ready(function() {
//If i click on edit button . I want to select the corresponding date and description .How can we do that?
$(".taskTemplate .edit").on('click', function(event) {
editTask($(this).siblings(".date, .desc"));
});
});
function editTask(nodes) {
var data = $.map(nodes, function(el) {
return `${el.className}: ${el.textContent}`
}).join(", ");
alert(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="taskTemplate">
<span class="date">205-10-09</span>
<span class="desc">description of task</span>
<input type="button" class="edit" value="edit">
<input type="button" class="delete" value="delete">
<span class="done">done</span>
</div>
<div class="taskTemplate">
<span class="date">2015-11-19</span>
<span class="desc">description of task2</span>
<input type="button" class="edit" value="edit">
<input type="button" class="delete" value="delete">
<span class="done">done</span>
</div>
Just replace parents()
by closest()
in :
var date = $(node).closest('.taskTemplate').find('.date').html();
Hope this helps.
$(document).ready(function() {
$(".taskTemplate .edit").on('click', function(event) {
editTask(event.target);
});
});
function editTask(node) {
var closest_div = $(node).closest('.taskTemplate');
var date = closest_div.find('.date').text();
var description = closest_div.find('.desc').text();
console.log(date, `|`, description);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="taskTemplate">
<span class="date">205-10-09</span>
<span class="desc">description of task</span>
<input type="button" class="edit" value="edit">
<input type="button" class="delete" value="delete">
<span class="done">done</span>
</div>
<div class="taskTemplate">
<span class="date">2015-11-19</span>
<span class="desc">description of task2</span>
<input type="button" class="edit" value="edit">
<input type="button" class="delete" value="delete">
<span class="done">done</span>
</div>