JQuery parent () function returns empty
I have the following html (simplified basic setup):
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(event)" />
</td>
</tr>
</table>
</div>
When I click on the image, a function is triggered findTheDiv(event)
that looks like this:
function findTheDiv(event) {
var elem = $(event.toElement);
var found = false;
// stop the loop if the top-level element is reached (html)
while (!$(elem).is("html")) {
if ($(elem).is("div.findme")) {
found = true;
break;
}
elem = $(elem).parent();
console.log(elem);
}
}
This is done, and for each iteration of the while loop, I write the new element that is the parent of the previous element to the console. As a result, I get:
[<img id="image" src="image.png" onclick="findTheDiv(event)">]
[<td>]
[<tr>]
[<table>]
[]
When the table is reached, it does not appear to have a parent, although that is clear as it is div
. To test this, I used the console to accomplish this:
$("table").parent();
And it returned an empty array
[]
Why does jQuery say there is no parent in the table since all elements except <html>
have parents?
source to share
jQuery function closest
already provides the function you are looking for, no need to reinvent the wheel:
function findTheDiv(e) {
var res = $(elem).closest('div.findme')
if (res. length) {
console.log('found it', res)
return true
}
console.log('the image is not inside a `div.findme`')
return false
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(this)" />
</td>
</tr>
</table>
</div>
source to share
I changed my code a bit and it works great. Instead of using an object event
as an argument, I just pass this
to refer to the object that fires the event directly. This serves the same purpose.
function findTheDiv(elem) {
//var elem = $(event.toElement);
var found = false;
// stop the loop if the top-level element is reached (html)
while (!$(elem).is("html")) {
if ($(elem).is("div.findme")) {
found = true;
break;
}
elem = $(elem).parent();
console.log(elem);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(this)" />
</td>
</tr>
</table>
</div>
Run the snippet, open a JavaScript console and see what it logs.
source to share