Pinguto Pinguto - 3 days ago 5
HTML Question

Enclose the text of the HTML tag that is out of other tags

I would like to make a small system for syntax highlighting in javascript for my web site.

My problem is that I can not find the text still highlighted.

A small example:


  • A possible input string:





<div class="keyword">for</div>
(
<div class="keyword">var</div>
i =
<div class="num">0</div>
; i <
<div class="num">10</div>
; i++){ app.food.
<div class="keyword">fn</div>
(); }






  • The results





<div class="keyword">for</div>
<div class="other">(</div>
<div class="keyword">var</div>
<div class="other"> i =</div>
<div class="num">0</div>
<div class="other">; i < </div>
<div class="num">10</div>
<div class="other">; i++){ app.food.</div>
<div class="keyword">fn</div>
<div class="other">(); }</div>





Can anyone help me? thanks!

Answer

With Jquery you can wrap the textNodes like this:

$('body').contents().filter(function() {
  return this.nodeType === 3
}).wrap('<div class="other">');
.other {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="keyword">for</div>
(
<div class="keyword">var</div>
i =
<div class="num">0</div>
; i &lt;
<div class="num">10</div>
; i++){ app.food.
<div class="keyword">fn</div>
(); }

Comments