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

我知道如何获取直接父类的值,id 等。但是,如何获取不是直接父类、也不是最大父类、而是已知类名的父类的 ID 值呢?我知道你会认为只是根据类名获取 ID 值。但我有很多动态加载的内容,具有相同的类。所以我必须拥有这个元素的父类。谢谢!


<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>


湖上湖
浏览 92回答 2
2回答

慕的地8271018

您可以尝试使用.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>

至尊宝的传说

访问最近祖先元素的不同方法是,closest(),parents(),querySelector和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');

慕工程0101907

使用.closest([class="2"])您可以获得匹配的祖先.2,并获取其ID:const input = document.querySelector('input');console.log(input.closest('[class="2"]').id);<div class="1">&nbsp; &nbsp; <div class="2" id="1">&nbsp; &nbsp; &nbsp; &nbsp; <div class="3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="4">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input class="need-ID-of-class-2" value="">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div>如果可能的话,修复您的 HTML,使其类有效 - 类名不应以数字开头。然后你可以使用.而不是[class]:const input = document.querySelector('input');console.log(input.closest('.two').id);<div class="1">&nbsp; &nbsp; <div class="two" id="1">&nbsp; &nbsp; &nbsp; &nbsp; <div class="3">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="4">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input class="need-ID-of-class-2" value="">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5