Iterating through each text element on the page?

I am trying to write a script in jQuery that will go through every text element inside the page. Then I need to change the color of each letter one by one. For example, for a page such as this:

<p>Some text and <a href="http://example.com">some link</a> and <span>something else</span></p> 

I would like to get:

 "Some text and " "some link" " and " "something else" 

and be able to stylize each individual letter (i.e. return it back to the DOM, whatever I call).

I know about the text() method, but this will not do the job, because it combines text content, while I need to access each individual text part.

Any suggestion on how to do this?

+6
source share
1 answer
  • Scroll through all child elements, recursively for elements.
    Keep all text nodes in a list.
  • Scrolling through all text nodes:
    • Scroll through the text content of each item.
      • Wrap each letter in the <span> element
      • Paste this item into DocumentFragment
    • Replace the text node with this snippet.

Demo: http://jsfiddle.net/B2uRn/

 // jQuery plugin, example: (function($) { $.fn.styleTextNodes = function() { return this.each(function() { styleTextNodes(this); }); }; })(jQuery) function styleTextNodes(element) { var span = document.createElement('span'); span.className = 'shiny-letter'; // Recursively walk through the childs, and push text nodes in the list var text_nodes = []; (function recursiveWalk(node) { if (node) { node = node.firstChild; while (node != null) { if (node.nodeType == 3) { // Text node, do something, eg: text_nodes.push(node); } else if (node.nodeType == 1) { recursiveWalk(node); } node = node.nextSibling; } } })(element); // innerText for old IE versions. var textContent = 'textContent' in element ? 'textContent' : 'innerText'; for (var i=text_nodes.length-1; i>=0; i--) { var dummy = document.createDocumentFragment() , node = text_nodes[i] , text = node[textContent], tmp; for (var j=0; j<text.length; j++) { tmp = span.cloneNode(true); // Create clone from base tmp[textContent] = text[j]; // Set character dummy.appendChild(tmp); // append span. } node.parentNode.replaceChild(dummy, node); // Replace text node } } 
+9
source

Source: https://habr.com/ru/post/909385/


All Articles