Find text string using jQuery?

后端 未结 7 1501
暖寄归人
暖寄归人 2020-11-22 07:38

Say a web page has a string such as \"I am a simple string\" that I want to find. How would I go about this using JQuery?

7条回答
  •  执笔经年
    2020-11-22 08:06

    This will select just the leaf elements that contain "I am a simple string".

    $('*:contains("I am a simple string")').each(function(){
         if($(this).children().length < 1) 
              $(this).css("border","solid 2px red") });
    

    Paste the following into the address bar to test it.

    javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;
    

    If you want to grab just "I am a simple string". First wrap the text in an element like so.

    $('*:contains("I am a simple string")').each(function(){
         if($(this).children().length < 1) 
              $(this).html( 
                   $(this).text().replace(
                        /"I am a simple string"/
                        ,'"I am a simple string"' 
                   )  
               ) 
    });
    

    and then do this.

    $('*[containsStringImLookingFor]').css("border","solid 2px red");
    

提交回复
热议问题