Need help to improve a code
What this code here does is that it gets a html, let's say, a banner, and inserts it after a element tag and after x number of words, but it differs what are html tags from what is text, this way, the code won't strip any html tags. In other words, this jquery code is supposed to get a banner and place it on the middle of a text (Blog post for example) without breaking the text's html. This code works, but it needs some improvements.
For example, if I specify it to insert the html after 300 words, but there is a tag (Div, h1, p, whatever) after the word 200 (At position 201), it simply won't show any result.
JS Fiddle demo.
Here are the problems that I'm facing:
- - It requires that all the words are held in a single text node; it doesn't even attempt to count words that might begin in one element and end inside of a sibling-element.
- - It doesn't allow – in its current implementation – any way of inserting non-text into the created-element (although this could be allowed via the use of
elem.innerHTML
in place of elem.textContent
), but it does return the created-element to the calling context so it can be cached or chained, which allows that created-element to be manipulated in some ways.
- - Some of the checks, if not most, are profoundly naive; and would benefit from extension to account for your own particular edge-cases.
The part responsible for getting the element is:
- // specifying the node into which the element
- // should inserted:
- 'node': document.querySelector('div > div')
The code:
- // a simple utility function to get only the actual words
- // from the supplied textNode (though this should work for
- // elements also):
- function getActualWords(node) {
-
- // gets the textContent of the node,
- // splits that string on one-or-more ('+')
- // white-space characters ('\s');
- // filters the array returned by split():
- return node.textContent.split(/\s+/).filter(function (word) {
- // word is the current array-element
- // (a 'word') in the array over
- // which we're iterating using
- // Array.prototype.filter();
- // here if the word, with leading
- // and trailing white-space removed
- // (using String.prototype.trim())
- // has a length greater than 0
- // (a falsey value) the word is kept
- // in the array returned by filter:
- return word.trim().length;
-
- // note that negative numbers are
- // also truthy, but no string can
- // have a negative length; so the
- // comparison is effectively, if
- // not explicitly 'greater than zero'
- // rather than simply 'not-zero'
- });
- }
-
- // named function to insert the specified
- // element after the nth word:
- function insertElemAfterNthWord(opts) {
-
- // defining the defaults for the function
- // (which can be overridden via the opts
- // Object):
- var defaults = {
-
- // the word after-which to insert the
- // the new element:
- 'nth': 5,
-
- // the text of the new element:
- 'elemText': 'new element',
-
- // the type of element (note no '<' or '>'):
- 'elemTag': 'div'
- };
-
- // iterating over the supplied opts Object to update
- // the defaults with the user-supplied options using
- // for...in loop:
- for (var prop in opts) {
-
- // if the opts Object has a property and
- // that property is not inherited from the
- // prototype chain:
- if (opts.hasOwnProperty(prop)) {
-
- // we set the defaults property
- // to the property-value held
- // in the opts Object:
- defaults[prop] = opts[prop];
- }
- }
-
- // aliasing the defaults object (simply to save
- // typing; this is not essential):
- var d = defaults,
-
- // ensuring that the supplied string,
- // specifying the element-type has no
- // '<' or '>' characters (to ensure validty
- // this should be extended further to
- // ensure only alphabetical characters are kept):
- tag = d.elemTag.replace(/<|>/g, ''),
-
- // creating the new element:
- elem = document.createElement(tag);
-
- // setting the textContent of the new element:
- elem.textContent = d.elemText;
-
- // ensuring that the d.nth variable is
- // a number, not a string, in base-10:
- d.nth = parseInt(d.nth, 10);
-
- // if a node was specified:
- if (d.node) {
-
- // setting the 'n' variable to hold
- // to the firstChild of the d.node:
- var n = d.node.firstChild,
-
- // using the utility function (above)
- // to get an Array of only the actual
- // words held in the node:
- words = getActualWords(n),
-
- // getting the number of words held
- // in the Array of words:
- wordCount = words.length;
-
- // while (n.nodeType is not a textNode OR
- // d.nth is a greater number than the number
- // of words in the node) AND the node has
- // a following sibling node:
- while ((n.nodeType !== 3 || d.nth > wordCount) && n.nextSibling) {
-
- // we update n to the next-sibling:
- n = n.nextSibling;
-
- // we get an array of words from
- // newly-assigned node:
- words = getActualWords(n);
-
- // we update the wordCount, in
- // order to progress through:
- wordCount = words.length;
- }
-
- // if the number of words is less than
- // the nth word after which we want to
- // insert the element, we return from
- // the function (doing nothing):
- if (getActualWords(n).length < d.nth) {
- return;
-
- // otherwise:
- } else {
-
- // again we get an Array of actual words,
- // we slice that Array and then get the
- // last array-element from that array,
- // using Array.prototype.pop():
- var w = getActualWords(n).slice(0, d.nth).pop(),
-
- // here we get the index of that word
- // (note that this is naive, and relies
- // upon the word being unique as a
- // proof-of-concept; I plan to update later):
- i = n.textContent.indexOf(w);
-
- // we split the n textNode into
- // two separate textNodes, at
- // supplied index ('i + w.length');
- // n remains the shortened 'first'
- // textNode:
- n.splitText(i + w.length);
-
- // navigating to the parentNode, and
- // using insertBefore() to insert the
- // new element ('elem') before the
- // next-siblin of the n textNode:
- n.parentNode.insertBefore(elem, n.nextSibling);
-
- // doing exactly the same, but adding a
- // newly-created textNode (of a space character)
- // between the 'n' textNode (which by definition
- // ends without a space) and newly-inserted
- // element:
- n.parentNode.insertBefore(document.createTextNode(' '), n.nextSibling);
-
- // joining adjacent, but unconnected,
- // textNodes (n and the newly-inserted
- // space character) together, to become
- // a single node:
- n.parentNode.normalize();
-
- // returning the newly-created element
- // so that it can be modified if required
- // or simply cached:
- return elem;
- }
-
- }
- }
-
-
- // calling the function, specifying the
- // user-defined properties:
- insertElemAfterNthWord({
- // after the tenth word:
- 'nth': 10,
- // the element-type (a span):
- 'elemTag': 'span',
-
- // setting the text of that new element:
- 'elemText': 'this is the newly-added text inside the newly-added element!',
-
- // specifying the node into which the element
- // should inserted:
- 'node': document.querySelector('div > div')
-
- // chaining the function, to use the Element.classList
- // API to add the 'newlyAdded' class to the
- // newly-created element:
- }).classList.add('newlyAdded');
References: