Buscar cadena de texto usando jQuery?


Digamos que una página web tiene una cadena como "Soy una cadena simple" que quiero encontrar. ¿Cómo lo haría usando jQuery?

 234
Author: BroSlow, 2009-05-29

7 answers

JQuery tiene el método contains. Aquí hay un fragmento para usted:

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("I am a simple string")');
});
</script>

El selector anterior selecciona cualquier elemento que contenga la cadena de destino. El foundin será un objeto jQuery que contenga cualquier elemento coincidente. Consulte la información de la API en: http://docs.jquery.com/Selectors/contains#text

Una cosa a tener en cuenta con el comodín '*' es que obtendrá todos los elementos, incluidos los elementos html y body, que probablemente no desee. Es por eso que la mayoría de los los ejemplos en jQuery y otros lugares usan di ('div:contains ("I am a simple string")')

 312
Author: Tony Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-10 20:25:44

Normalmente los selectores jQuery no buscan dentro de los "nodos de texto" en el DOM. Sin embargo, si se utiliza el .contents (), se incluirán nodos de texto, luego puede usar la propiedad NodeType para filtrar solo los nodos de texto y la propiedad nodeValue para buscar la cadena de texto.

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });
 48
Author: BarelyFitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-29 16:20:21

Esto seleccionará solo los elementos de la hoja que contienen "Soy una cadena simple".

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

Pegue lo siguiente en la barra de direcciones para probarlo.

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

Si quieres agarrar solo "Soy una cadena simple". Primero envuelva el texto en un elemento como este.

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

Y luego hacer esto.

$('*[containsStringImLookingFor]').css("border","solid 2px red");
 26
Author: Slim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-13 03:57:37

Si solo desea el nodo más cercano al texto que está buscando, puede usar esto:

$('*:contains("my text"):last');

Esto incluso funcionará si su HTML se ve así:

<p> blah blah <strong>my <em>text</em></strong></p>

Usando el selector anterior encontrará la etiqueta <strong>, ya que es la última etiqueta que contiene esa cadena completa.

 16
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-29 16:49:42

Echa un vistazo a highlight (plugin jQuery).

 12
Author: Chris Doggett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-29 15:25:26

Simplemente agregando a la respuesta de Tony Miller, ya que esto me llevó al 90% hacia lo que estaba buscando, pero aún así no funcionó. Agregar .length > 0; al final de su código hizo que mi script funcionara.

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });
 5
Author: Pixelomo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 02:50:51

Esta función debería funcionar. básicamente hace una búsqueda recursiva hasta obtener una lista distinta de nodos hoja.

function distinctNodes(search, element) {
    var d, e, ef;
    e = [];
    ef = [];

    if (element) {
        d = $(":contains(\""+ search + "\"):not(script)", element);
    }
    else {
            d = $(":contains(\""+ search + "\"):not(script)");
    }

    if (d.length == 1) {
            e.push(d[0]);
    }
    else {
        d.each(function () {
            var i, r = distinctNodes(search, this);
            if (r.length === 0) {
                e.push(this);
            }
            else {
                for (i = 0; i < r.length; ++i) {
                    e.push(r[i]);
                }
            }
        });
    }
    $.each(e, function () {
        for (var i = 0; i < ef.length; ++i) {
            if (this === ef[i]) return;
        }
        ef.push(this);
    });
    return ef;
}
 2
Author: danatcofo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-13 18:42:06