How to get the ID value of a parent element by class that is not immediate? jQuery

Viewed 454

I know how to get the value of an immediate parents class,id..etc.. But how do you get the ID value of a parent that is not immediate, and not the grandest-parent, but of a known class name? I know you would think just to get the ID value based on the class name. But I have a lot of dynamically loaded content, with the same classes. So I must have the class that is a parent of THIS element. Thanks!

<div class="A">
    <div class="B" id="1">
        <div class="C">
            <div class="D">
                <input class="need-ID-of-class-B" value="">
            </div>
        </div>
    </div>
</div>
3 Answers

You can try with .parents() OR .closest():

console.log($('.need-ID-of-class-2').closest('.2').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
  <div class="2" id="1">
    <div class="3">
      <div class="4">
        <input class="need-ID-of-class-2" value="">
      </div>
    </div>
  </div>
</div>

With .closest([class="2"]) you can get an ancestor matching .2, and get its ID:

const input = document.querySelector('input');
console.log(input.closest('[class="2"]').id);
<div class="1">
    <div class="2" id="1">
        <div class="3">
            <div class="4">
                <input class="need-ID-of-class-2" value="">
            </div>
        </div>
    </div>
</div>

If at all possible, fix your HTML so that its classes are valid - class names should not start with a number. Then you can use . instead of [class]:

const input = document.querySelector('input');
console.log(input.closest('.two').id);
<div class="1">
    <div class="two" id="1">
        <div class="3">
            <div class="4">
                <input class="need-ID-of-class-2" value="">
            </div>
        </div>
    </div>
</div>

Different ways to access nearest ancestor elements are, closest(), parents(), querySelector with closest().

$('.need-ID-of-class-B').closest('.B').attr('id');

$('.need-ID-of-class-B').parents('.B').attr('id');

document.querySelector('.need-ID-of-class-B').closest("div .B").getAttribute('id');
Related