Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not really clear what kind of "HTML" you are working on. If it is HTML <em>code</em>, something from an Ajax request maybe, then you can use a regular expression; matching both a link <em>or</em> the pattern, and then work out what to do in a callback:</p> <pre><code>var html = document.body.innerHTML; html = html.replace(/(&lt;a\s.*?&gt;.*?&lt;\/a&gt;)|(\?\?\?([a-z0-9.]*)\?\?\?)/g, function ( a, b, c, d ) { return ( a[0] == '&lt;' ) ? a : '&lt;a href="#"&gt;' + d + '&lt;/a&gt;'; }); context.innerHTML = html; </code></pre> <p>Conveniently, <code>replace()</code> <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace" rel="nofollow noreferrer">can take a callback function</a> as a replacement generator rather than a simple string.</p> <p>If you are working on a live DOM tree, however, you might want to respect events on nodes and not simply reset the <code>innerHTML</code>. You'll need a bit more primitive approach for that:</p> <pre><code>// returns all childnodes of type text that do not have A as parent function walker ( node ) { var nodes = []; for (var c, i = 0; c = node.childNodes[i]; i++) { if ( c.nodeType === 1 &amp;&amp; c.tagName !== 'A' ) { nodes = nodes.concat( arguments.callee( c ) ); } else if ( c.nodeType === 3 ) { nodes.push( c ); } } return nodes; } var textNodes = walker( document.body ); for (var i = 0; i &lt; textNodes.length; i++) { // create an array of strings separating the pattern var m = textNodes[i].nodeValue.split( /(\?\?\?([a-z0-9.]*)\?\?\?)/ ); if ( m.length &gt; 1 ) { for (var j=0; j&lt;m.length; j++) { var t, parent = textNodes[i].parentNode; // create a link for any occurence of the pattern if ( /^\?\?\?([a-z0-9.]*)\?\?\?$/.test( m[j] ) ) { var a = document.createElement( 'a' ); a.href = "#"; a.innerHTML = RegExp.$1; // m[j] if you don't want to crop the ???'s parent.insertBefore( a, textNodes[i] ); t = document.createTextNode( ' ' ); // whitespace padding } else { t = document.createTextNode( m[j] ); } parent.insertBefore( t, textNodes[i] ); } // remove original text node parent.removeChild( textNodes[i] ); } } </code></pre> <p>This method only touches textnodes, and then only those that match the pattern.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload