0

I have the HTML as follows. what i need is when someone clicks on the span element i want to find its parents parent element check some conditions. i used prev() method but it gives me only the near parent(parent2 here)

<div class="container">
    <div class="contain">
        <div id="parent1">
            <div class="parent2">
                <span> Click here</span>
            </div>
        </div>
    </div>
</div>

var currentComponent = $(event.target).prev(); //here i get parent2

How can i find the parents parent element(in this case parent2). i am not very familiar with jquery so any help would be appreciated.

Sha
  • 1,826
  • 5
  • 29
  • 53

4 Answers4

4

You can try .closest.

From the docs:

the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. (...) get the first element that matches the selector by testing the element itself and .

It traverses up through the element ancestors in the DOM and returns the first one that matches the selector you passed as an argument. So, in your example, you can do something like that:

$("span").on("click", function(e) {
  var myParent = $(this).closest(".parent2");
  var parentOfMyParent = $(this).closest(".parent1");
  var contain = $(this).closest(".contain");
  var containerAbove = $(this).closest(".container");
});
mrlew
  • 7,078
  • 3
  • 25
  • 28
1

What you need is

var currentComponent = $(event.target).parent().parent()

To do it in a single call, you can use

var currentComponent = $(event.target).closest(".parent1")
Anomitra
  • 1,111
  • 15
  • 31
1

Fiddle:

https://jsfiddle.net/c624re4o/

Code:

var grandParent = $(this).parent().parent();

Full Working Code

$(document).ready(function () {
  $("span").click(function () {
    var grandParent = $(this).parent().parent();
    alert(grandParent.attr('id')); // Just for Testing
  });
});

$(document).ready(function () {
  $("span").click(function () {
    var grandParent = $(this).parent().parent();
    alert(grandParent.attr('id')); // Just for Testing
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="contain">
        <div id="parent1">
            <div class="parent2">
                <span> Click here</span>
            </div>
        </div>
    </div>
</div>
David R
  • 14,711
  • 7
  • 54
  • 72
Ahsan
  • 1,084
  • 2
  • 15
  • 28
1

you can use .closest() or .parents() function with selector like .parents('#elementid')

Alam Zaib
  • 187
  • 1
  • 11