简体   繁体   English

如何通过非直接类获取父元素的 ID 值? jQuery

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

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?我知道如何获取直接父类的值,id..等。但是你如何获取不是直接的父类的 ID 值,不是最祖父类,而是已知类名的 ID 值? I know you would think just to get the ID value based on the class name.我知道您会认为只是根据类名获取 ID 值。 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>

You can try with .parents() OR .closest() :您可以尝试使用.parents().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:使用.closest([class="2"])您可以获得匹配.2的祖先,并获取其 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.如果可能,请修复您的 HTML 以使其类有效 - 类名不应以数字开头。 Then you can use .然后你可以使用. instead of [class] :而不是[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() .访问最近祖先元素的不同方法是,最近的()父母()querySelector 和最近的()

$('.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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM