Reputation: 105
The use of "this" and ".parent()" in jquery gets a bit confusing when it goes past simple divs or datatables. I have a table with the following structure: (I can't rename any of the classes or id)
<table class="table1">
<tbody>
<tr>
<div class="detail">
<table>
<thead></thead>
<tbody>
<tr>
<td>
<img class="picture_open" src="../location">
</td></tr></tbody></table></div></tr></tbody></table>
What I'm trying to do is have a click function on that img which will be able to grab the full RowElement.
What I have now:
$(".table1 tbody tr td img.picture_open").live('click', function () {
var overallTable = jQuery(this).parent("table").dataTable();
console.log("overallTable: " + overallTable);
var elementRow = this.parentNode.parentNode;
console.log("elementRow: " + elementRow);
var rowData = overallTable.fnGetData( elementRow );
console.log("rowData: " + rowData);
if ( this.src.match('img_name') )
{
//kills the table that was created if that row is opened
}
else
{
//runs ajax call to create another table since row is NOT opened
}
} );
However the code I have above prints out this: overallTable: [object Object] elementRow: [object HTMLTableRowElement] TypeError: 'null' is not an object (evaluating 'oSettings.aoData')
In my problem is the $(this) incorrect? (Not getting the img with class "picture_open") Or is my overallTable variable set up incorrectly with the .parent()? Or is it my elementRow variable set up improperly with the parentNode? Any help to clarify my errors would be amazing.
Thanks!
Upvotes: 0
Views: 8958
Reputation: 169
Try this :
$('.table1').on('click', '.picture_open', function(ev) {
this // is .picture_open element
ev.target // is .picture_open element
ev.delegateTarget // is .table1 element
var $row = $(ev.delegateTarget).find('.detail tr').first();
});
Upvotes: 1
Reputation: 20313
parent()
in jQuery will parse only one level up the DOM, you should use .parents()/.closest()
. This will fix your issue.
NOTE: .live()
is turned into .on()
in latest jQuery versions. Better to use .on()/.click()
Upvotes: 1
Reputation: 15112
You need to use .closest('table')
to find the closest table
Similary to find the element row
var elementRow = $(this).closest('tr');
Upvotes: 0
Reputation: 5845
in jQuery, .parent() only goes up the DOM once. What you should be using it .parents() to look up the DOM until it finds table
Upvotes: 0
Reputation: 1433
parent()
in jQuery only moves one level up the DOM, so what you probably want there is parents('table')
. This should fix your overallTable issue.
Upvotes: 0