2

I there way to get element from DOM objects whitch contains some string? I am trying:

$( "*:contains('searchedString')" ).first().text( "test" );

or

$( "*:contains('searchedString')" ).text( "test" );

But this returns <html> object so after execute whole content dissapear and show only test on screen.

EDIT:

  • I need search in whole document therefore * selector...
  • DOM types can be h2, div, etc..
Lajdák Marek
  • 2,969
  • 8
  • 29
  • 58

3 Answers3

4

Getting everything with * will always include the <html> tag.

To get the deepest element, you could get the last element your selector finds using jQuery .last() method :

<div><span>test</span></div>

let deepestElement = $("*:contains('test')").last();
console.log(deepestElement);

Here is a working JSFiddle : https://jsfiddle.net/Zenoo0/ryjtwdqb/2/

Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

You can get all the result which has no child as below:

var result = $( "*:contains('searchedString'):not(:has(*))" ).text( "test" );
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>searchedString</span>
</div>

Or You can limit the selector with tags to avoid results you don't want.

And you can use filter to get the useful part.

var tags = ['div', 'p', 'span'];
var str = "";
var result = $(tags.join(',')).filter(':contains("searchedString")');
console.log(result.length);
// ... filter result or something
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>searchedString</span>
</div>
Terry Wei
  • 1,521
  • 8
  • 16
0
$( "h1,h2,div:contains(searchStrinng)" ).first().text( "test" );
$( "h1,h2,div:contains(searchStrinng)" ).text( "test" );

Example:
<h1>Hello</h1>
<h2>Hello</h2>

- For first element (include only h1,h2,div) 
$( "h1,h2,div:contains(Hello)" ).first().text( "test" );

- For all element(include only h1,h2,div)
$( "h1,h2,div:contains(Hello)" ).text( "test" );