Search code examples
jqueryselectorparent

Finding a parent with jQuery


I have this code below:

<div class="as-mobile-item as-mobile-question">
    <label>Test</label>
    <div>
        <textarea name="as_items" class="form-control input-lg as-task-input as-section-ending" rows="3"></textarea>
    </div>
</div>

Given as-section-ending, what selector can I use to get the highest level div? The one with classes as-mobile-item as-mobile-question?

I can't just use a selector for those classes because they exist elsewhere. I specifically need to get the div where those classes have that as-section-ending child.

Thanks


Solution

  • Use .closest

    Like this

    $(function() {
      var $parentDivs = $(".as-section-ending").closest("div.as-mobile-item.as-mobile-question");
      alert($parentDivs.find("label").text()); // for example
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="as-mobile-item as-mobile-question">
      <label>elsewhere</label>
    </div>
    <div class="as-mobile-item as-mobile-question">
      <label>Test</label>
      <div>
        <textarea name="as_items" class="form-control input-lg as-task-input as-section-ending" rows="3"></textarea>
      </div>
    </div>