innerHTML: How To Avoid

前端 未结 5 460
孤城傲影
孤城傲影 2021-01-02 16:00

I\'m writing a plugin which will convert emoticons to images in a text block for a particular site. The easy answer is to use regular expressions to detect the trigger text

5条回答
  •  感动是毒
    2021-01-02 16:54

    Working Solution

    Based on your recent comment to @Giuseppe, and your malformed styling that you borrowed from my post the only solution would be to avoid recursion or iterating through the text strings looking for matching elements for your regEx.

    1. Apply the regex to your string as you are proposing.
    2. Once finished build a DOM from that string using a HTMLify string parser
    3. Replace the node with the new DOM node built from the string.

    NB: This is also useful when pulling in AJAX HTML page and you need to parse the HTML results in a temporary DOM object but don't want to merely dump the contents into a the innerHTML of a newly created element. Also note that using createDocumentFragment will not be suitable as you cannot navigate a fragment like a DOM tree.

    The steps sound hard but there are a few great posts on Stackoverflow which make it easy!
    After doing research for you and running into a now obsolete solution and dom parsers which won't work for you I came across a solution from @rob-w: a dom parser

    Your code would include the DOM parser from @rob-w link plus:

         /* 
          * DOMParser HTML extension 
          * 2012-02-02 
          * 
          * By Eli Grey, http://eligrey.com 
          * Public domain. 
          * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 
          */
         /*! @source https://gist.github.com/1129031 */
         /*global document, DOMParser*/ 
                 (function (DOMParser) {
             "use strict";
             var DOMParser_proto = DOMParser.prototype;
             var real_parseFromString = DOMParser_proto.parseFromString;
    
             // Firefox/Opera/IE throw errors on unsupported types  
             try {
                 // WebKit returns null on unsupported types  
                 if ((new DOMParser).parseFromString("", "text/html")) {
                     // text/html parsing is natively supported  
                     return;
                 }
             } catch (ex) {}
    
             DOMParser_proto.parseFromString = function (markup, type) {
                 if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
                     var doc = document.implementation.createHTMLDocument("");
                     var doc_elt = doc.documentElement;
                     var first_elt;
    
                     doc_elt.innerHTML = markup;
                     first_elt = doc_elt.firstElementChild;
    
                     if (doc_elt.childElementCount === 1 && first_elt.localName.toLowerCase() === "html") {
                         doc.replaceChild(first_elt, doc_elt);
                     }
    
                     return doc;
                 } else {
                     return real_parseFromString.apply(this, arguments);
                 }
             };
         }(DOMParser));
    
         autostyle = function (str) {
             var boldPattern = /(?![^<]*<\/a>)(^|<.>|[\s\W_])\*(\S.*?\S)\*($|<\/.>|[\s\W_])/g;
             var italicsPattern = /(?![^<]*<\/a>)(^|<.>|[\s\W])_(\S.*?\S)_($|<\/.>|[\s\W])/g;
             var strikethroughPattern = /(?![^<]*<\/a>)(^|<.>|[\s\W_])-(\S.*?\S)-($|<\/.>|[\s\W_])/gi;
             var underlinePattern = /(?![^<]*<\/a>)(^|<.>|[\s\W_])!(\S.*?\S)!($|<\/.>|[\s\W_])/gi;
             str = str.replace(strikethroughPattern, '$1$2$3');
             str = str.replace(italicsPattern, '$1$2$3');
             str = str.replace(boldPattern, '$1$2$3');
             str = str.replace(underlinePattern, '$1$2$3');
             return str;
         };
    
         emoticonRegexFunction = function(str) {
             //do something
             return str;
         }
    
         RegexWithoutInnerHTML = function () {
             pItems = document.getElementsByTagName('p');
             for (var k = 0; k < pItems.length; k++) {
                 var str = pItems[k].textContent;
                 str = autostyle(str);
                 str = emoticonRegexFunction(str);
                 var doc = new DOMParser().parseFromString('

    ' + str + '

    ', 'text/html'); pItems[k].parentNode.replaceChild(doc.getElementsByTagName('p')[0], pItems[k]); // pItems[k].innerHTML = str; //<-now do not need innerHTML } };

    Full working example on jsbin at: http://jsbin.com/itiwek/12/edit

    Enjoy.

提交回复
热议问题