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?

+3


source to share


2 answers


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>
      

Run codeHide result


+1


source


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 codeHide result


Run the snippet, open a JavaScript console and see what it logs.

+2


source







All Articles