替换<pre> without <code> to <pre> <code> once only

时间:2017-04-24 17:14:41

标签: javascript

How to replace just <pre> which is not already wrapping <code> with <pre><code> using jquery or javascript.

Example:

I have code like:

<pre>&lt;p&gt;Hello&lt;/p&gt;</pre> <-- Target

<pre><code>&lt;p&gt;Hello World&lt;/p&gt;</code></pre>

I need change only <pre> like this:

<pre><code>&lt;p&gt;Hello&lt;/p&gt;</code></pre>  <-- Only change this <pre>

<pre><code>&lt;p&gt;Hello World&lt;/p&gt;</code></pre>

Check my problem below site: http://www.web-development.cf/p/testting-page.html

3 个答案:

答案 0 :(得分:0)

感谢&#34; Alon Eitan&#34;。

我使用这个jquery完成了我的问题:

$("pre:not(:has(code))").each(function() { $(this).wrapInner( "<code></code>") });

在网站下方检查我的问题:web-development.cf/p/testting-page.html

答案 1 :(得分:-1)

Ick.

Regex I guess.

function replace(html) {
  return html
    // Look-ahead for <code>
    .replace(/(<pre>)(?!<code>)/gi, '<pre><code>')
    // Look-behind for </code>
    .replace(/(<\/pre>)/gi, function(m, g, i, s) {
      return s.slice(i-7, i) === '</code>'
        ? m
        : '</code></pre>'
      })

}

replace('<pre>&lt;p&gt;Hello&lt;/p&gt;</pre>')
// returns "<pre><code>&lt;p&gt;Hello&lt;/p&gt;</code></pre>"

replace('<pre><code>&lt;p&gt;Hello World&lt;/p&gt;</code></pre>') 
// returns "<pre><code>&lt;p&gt;Hello World&lt;/p&gt;</code></pre>"

答案 2 :(得分:-1)

You question is definitely unclear, but if I understand correctly, you want to basically add a tag into any tags that don't already contain .

This can be done by getting all of the tags, and then looking at its children to see if there is a tag:

function fillInMissingTags(outerTag, innerTag) {
    var elements = document.getElementsByTagName(outerTag);
    for(var elementIndex = 0, elementsLength = elements.length; elementIndex < elementsLength; elementIndex++) {
        var element = elements[elementIndex],
            found = false
            html;

        for(var childIndex = 0, childrenLength = element.children.length; childIndex < childrenLength; childIndex++) {
            var child = element.children[childIndex];
            if(child.tagName.toLowerCase() === innerTag) {
                found = true;
                html = element.innerHTML;
                break;
            }
        }

        if(found !== true) {
            var codeElement = document.createElement(innerTag);
            codeElement.innerHTML = html;
            element.innerHTML = codeElement;
        }
    }
}

fillInMissingTags('pre', 'code');

This would only handle checking for in the immediate children. If you wanted to do a deep check, you would need to modify it to check the children recursively.

EDIT I made it more generic so you can use the method to wrap the insides of any element that is missing a proper child.