Joel
Joel

Reputation: 6107

Searching an element with specific text in jQuery

I want to get an element that contains specific text. When I use the :contains selector, the result is also all of the parents elements of that specific element.

Also, if there is more than on element that actually contains the text, the result of the selector is very cumbersome. Is it possible to get only the elements themselves which contains the specific text?

Thanks, Joel

EDIT:

Example:

<body>
    <div>
        <div>
            <div>text</div>
        </div>
    </div>
</body>

and $("div:contains('text')") results in:

[<div>​…​</div>​, <div>​…​</div>​, <div>​text​</div>​]

I want a way to only get the <div>text</div> element. (I know I can use .get(-1) to get that last element, but I want to know if there is something more gemeric).

Upvotes: 1

Views: 82

Answers (2)

Ali Foroughi
Ali Foroughi

Reputation: 4619

i do not khow this way work right , but you check it , if it was not work, comment me to edit it for an other solution

$("div[innerHTML=text]")

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

You can try something like:

$(":contains('text')").each(function() {
  if($(this).find(":contains('text')").length > 0) {
    // ignore. this is just an element containing at least 1 child containing 'text'
  }
  else {
    // this is an element you want, directly contains 'text'
    // .. your code here ..
  }
});

Upvotes: 3

Related Questions