T
T
troi2018-06-26 11:11:43
JavaScript
troi, 2018-06-26 11:11:43

How to select all characters of the Russian alphabet on the page, provided that the attributes of some elements may contain it?

How to select all characters of the Russian alphabet on the page, provided that the attributes of some elements may contain it?
My attempts to solve the problem are attached:

<html>
  <head>
    <script type="text/javascript">
      function search_rus_symbol() 
        {
          document.getElementById('www1').innerHTML = document.getElementById('www1').innerHTML.replace(/(ext:qtip=")([а-яё\s]+)(")(\S)([а-яё\s]+)/gim,'<font color="red">$5</font>');
          //document.getElementById('www1').innerHTML = document.getElementById('www1').innerHTML.replace(/([а-яё])/gi,'<font color="red">$1</font>');
        }
    </script> 
  </head>
  <body onload="search_rus_symbol()" id="www1">
    <div>
      <table class="x-grid3-row-table" border="1" width="100%" cellpadding="5">
        <tr>
          <th>Ячейка 1</th>
          <th>Ячейка 2</th>
        </tr>
        <tr>
          <td>Ячейка 3</td>
          <td>Ячейка 4</td>
          <td class="x-grid3-col x-grid3-cell x-grid3-td-name " style="width:646px;" tabindex="-1">
            <div class="x-grid3-cell-inner x-grid3-col-name" ext:qtip="Текст атрибута">текст, у которого все русские символы должны быть красными</div>
          </td>
        </tr>
      </table>
    </div>
      <br>текст в боди после закрывающего тега див
  </body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-06-26
@troi

We need to recursively traverse the entire DOM tree and consider only text nodes. Regular replace one-or-several-consecutive characters from the Cyrillic alphabet (+spaces, perhaps) with them, in the wrapper from the formatting tag.

More or less like this
function replacer(el){
  var i, node, span;
  if(el.hasChildNodes()) {
    for(i=0; i<el.childNodes.length; i++) {
      node = el.childNodes[i];
      if(node.nodeType === Node.ELEMENT_NODE) {
        if( !!~['SCRIPT','NOSCRIPT'].indexOf(node.nodeName)) continue;
        replacer(node);
      } else if( node.nodeType === Node.TEXT_NODE) {
        if(node.nodeValue.match(/^\s+$/)) continue;
        span = document.createElement("span");
        span.innerHTML = node.nodeValue.replace(/([а-яА-Я]+)/ug, '<i>$1</i>');
        el.insertBefore(span, node);
        el.removeChild(node);
      }
    }
  }
}

replacer(document.body);

Here, for simplicity, I cheated and in general I replace each text node with to simply replace innerHTML with it. Fiddle<span>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question