Ver Mensaje Individual
  #4 (permalink)  
Antiguo 13/02/2014, 10:25
Avatar de jonni09lo
jonni09lo
Colaborador
 
Fecha de Ingreso: septiembre-2011
Ubicación: Estigia
Mensajes: 1.471
Antigüedad: 12 años, 7 meses
Puntos: 397
Respuesta: Buscar palabra en div que no pertenezca a una etiqueta

Hola @NSD el tema es un poco complicado, pero a partir de esta idea sale el siguiente código:

Código Javascript:
Ver original
  1. var matchText = function(node, regex, callback) {
  2.     var child = node.firstChild;
  3.     do {
  4.         if (child.nodeType === 3) {
  5.             child.data.replace(regex, function(all) {
  6.                 var args = [].slice.call(arguments),
  7.                     offset = args[args.length - 2];
  8.                 if(offset > child.data.length){
  9.                     offset = child.data.indexOf(all);
  10.                 }
  11.                 var newTextNode = child.splitText(offset);
  12.                 newTextNode.data = newTextNode.data.substr(all.length);
  13.                 callback.apply(window, [child].concat(args));
  14.                 child = newTextNode;
  15.             });
  16.         }
  17.     } while (child = child.nextSibling);
  18.  
  19.     return node;
  20. }
  21. var searchTerm = 'texto';
  22. matchText(document.getElementById("textoid"), new RegExp("\\b" + searchTerm + "\\b", "g"), function(node, match, offset) {
  23.     var span = document.createElement("span");
  24.     span.textContent = match;
  25.     node.parentNode.insertBefore(span, node.nextSibling);
  26. });

DEMO

Saludos
__________________
Haz preguntas inteligentes-Como ser Hacker
No hacer preguntas por mensaje privado. No sólo no es inteligente sino que es egoísta.

Última edición por jonni09lo; 13/02/2014 a las 10:30