Trevor Trevor - 1 month ago 5x
Javascript Question

Manipulate text value of jQuery nodes

I selected all nodes on an HTML page like so:

var all = $('*');

I then traverse each node, checking to see if each has an associated text value:

var newDom =, node) => {
if ($(node).text()) {
var temp = $(node).text() + 'a';

I ultimately want to view the manipulated DOM in the browser. Without the above manipulation,
yields the exact webpage that was selected, as we would expect. Meanwhile,
yields the following error:

Unhandled rejection Error: getaddrinfo ENOTFOUND on.ico on.ico:80
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:79:26)

At first glance, why might this not be working as I have it above?


There is no selector for text nodes, however you can write a recursive function to get them all as an array based on a root node. Then you can loop over the array and do stuff to the text nodes, e.g.

/* Return all text nodes that are descendents of root as an array
** @param {DOMElement} root - node to start from, defaults to document.body
** @returns {Array} array of all text nodes that are descendents of root
function getTextNodes(root) {
  var root = root || document.body;
  var textNodes = [];
  // Don't process text inside these nodes
  var elementsToIgnore = {'script':true};

  if (root && root.nodeType == 1) { || [root], function(node) {

      if (node.nodeType == 1 && node.tagName && !(node.tagName.toLowerCase() in elementsToIgnore)) {
        textNodes = textNodes.concat(getTextNodes(node));

      } else if (node.nodeType == 3){
  } else if (root.nodeType == 3) {
  return textNodes;
 <p>Here is some text</p>
   <li>List item 1
   <li>List item 2
       <li>List item 2.1
       <li>List item 2.3
   <li>List item 3
  <textarea>Gets text in here too</textarea>

  <button onclick="getTextNodes().forEach(function(node){ =,'$')})">Replace all 's' with $</button>