Search code examples
jqueryhtmlparentparents

get specific parent in jQuery


I have the following HTML and I need to get the first div parent of the object (collapse)

If this parent has a class of (ZeroClass) .. I want to have the next div parent ..

<div>
  <div id = "DeadCode">
    <div class = "ZeroClass">
      <table class = "zeroTable">
         <...tableData...>
      </table>
    </div>
  </div>
</div>

the jQuery Function :

function ResizeGrid(){
    var collapse = $(".zeroTable").parent();

    if ($(collapse).hasClass("ZeroClass")) {
        collapse = $(collapse).parents($("div"));
    }
}

Everything goes fine but when passing through the if statement, it makes Collapse Null .. any ideas?


Solution

  • Use parent for the first step and closest for the second:

    function ResizeGrid() {
        var $collapse = $(".zeroTable").parent();
    
        if ($collapse.hasClass("ZeroClass")) {
            $collapse = $collapse.closest("div");
        }
    }
    

    Your problem lies in this row:

    collapse = $(collapse).parents($("div"));
    

    You first fetch ALL div elements $("div") and then tell $(collapse).parents() to match one of them.

    My code:

    $collapse = $collapse.closest("div");
    

    Tells jQuery to find the closest parent div.

    It's a good practice to prefix jQuery variables with $ to help keep track of which vars are jQuery objects and which are regular DOM nodes.