Reputation: 3069
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:
*
selector...Upvotes: 2
Views: 2985
Reputation: 44
$( "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" );
Upvotes: 0
Reputation: 1531
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>
Upvotes: 0
Reputation: 12880
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/
Upvotes: 4