Search code examples
javascriptjquerydomcontain

Jquery find string in DOM and get his element


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

Solution

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