如何使用 jquery 获得精确的 div 标签匹配选择器?

How to get exact div tag matching selector using jquery?

我想获得匹配 jquery 选择器的确切标签(不是父标签)。 这是我的代码:

var tagList = $('div:contains("Hello")');
alert(tagList.length);

此选择器 returns 标签列表(长度为 4),它们都是匹配标签的父 div。

<div>
  <div>
     <div>
        <div> Hello </div>   //I want to get only this element
     </div>
  </div>
     <div>     //I also tried to get deepest children but result contains this siblings of parents too.
     </div>
</div>

如何将结果减少到只有一个符合规则的元素。

这里我是用filter的方法来检查children,如果有没有child,那么就是您想要的元素

Learn more about contains,filter and wrap methods of jQuery

var tagList = $('div:contains("Hello")').filter(function(){
    return this.children.length === 0;
  });
console.log(tagList.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div>
     <div>
        <div> Hello </div>
     </div>
  </div>
  <div>
  </div>
</div>

你可以设置一个id来识别div

var tagList = $('#hello').text();
alert(tagList.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div>
  <div>
    <div>
      <div id="hello">Hello</div>
    </div>
  </div>
  <div>     //I also tried to get deepest children but result contains this siblings of parents too.
  </div>
</div>