0

I want to get the exact tag (not parents) that matching jquery selector. this is my code:

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

this selector returns a list of tag (length is 4) that are all parent div of matching tag.

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

How to reduce result to only one element that matching the rule.

MeirDayan
  • 620
  • 5
  • 20
  • Take the [last](https://api.jquery.com/last/#last) element from the returned jQuery object ..? – Teemu Jul 08 '20 at 05:54
  • Does this answer your question? [jQuery: find element by text](https://stackoverflow.com/a/22778570/2185135) – Lowkey Jul 08 '20 at 05:58

2 Answers2

1

Here I am using filter method to check children, If it has no child, Then that's the element that you want.

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>
BadPiggie
  • 5,471
  • 1
  • 14
  • 28
0

you can set an id to identify the 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>
Dinesh
  • 812
  • 4
  • 14
  • 1
    Cannot set id for dynamic data. The same time, The text content can be exist in may elements along with other texts. But you can't set same id for each. – BadPiggie Jul 08 '20 at 06:01
  • 1
    I don't want to set id. – MeirDayan Jul 08 '20 at 06:12
  • These days, it's best to avoid setting IDs unless you have a specific reason to use one. They clutter up the global scope. Browsers are plenty fast at using selectors, and the APIs have been improved for many years now. – Brad Jul 08 '20 at 16:32