ZicoPL ZicoPL - 1 year ago 49
jQuery Question

wrap words in all same selectors with using Dom Objec

I get a code from webhelp.pl forum: Fiddle, which wrap any word in first selector:


but when I'd like to add the same for rest 'p' selectors by:


then code no work. Could someone help me?

Answer Source

querySelector() returns a single element, which may contain child nodes.

querySelectorAll() returns a list of elements – each of which may contain child nodes. But the list itself does not have a childNodes property.

You need to iterate through the querySelectorAll() list to operate on each of its elements child nodes in turn:

Array.prototype.slice.call(document.querySelectorAll('.abcd')).forEach(function(p) {
  Array.prototype.slice.call(p.childNodes).forEach(function (node) {
    if (node.nodeType === Node.TEXT_NODE) {
      var text = node.nodeValue;

      var words = text.match(/(\S+|\s+)/g);

      words.forEach(function (word) {
        var isWhiteSpace = /^\s+/.test(word);

        if (isWhiteSpace) {
          node.parentNode.insertBefore(document.createTextNode(word), node);
        } else {
          var span = document.createElement('span');
          span.textContent = word;
          node.parentNode.insertBefore(span, node);



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download