dom wrapping a substring in textnode with a new span node

Suppose, I have this paragraph:

<p>this is a paragraph containing link to an image at http://lol/atme.png :)</p>

I want to replace http://lol/atme.png with an image element. How do I do that? Its like removing the text, but adding a image element in place of that text.

Help will be greatly appreciated.

Answers:

Answer

There are two parts to this. The first is the extraction of the URLs from the text, which is a tricky issue I'm not that interested in. I would do some research before using this in production. For now, I'll use an extremely simple illustrative regex.

The second part is the code for doing the replacement within text nodes. I answered a related question the other day with some reusable code and now I'm getting to reuse it. Yay.

function createImage(matchedTextNode) {
    var el = document.createElement("img");
    el.src = matchedTextNode.data;
    el.width = 30;
    el.height = 20;
    return el;
}

function surroundInElement(el, regex, surrounderCreateFunc) {
    var child = el.lastChild;
    while (child) {
        if (child.nodeType == 1) {
            surroundInElement(child, regex, createImage);
        } else if (child.nodeType == 3) {
            surroundMatchingText(child, regex, surrounderCreateFunc);
        }
        child = child.previousSibling;
    }
}

function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
    var parent = textNode.parentNode;
    var result, surroundingNode, matchedTextNode, matchLength, matchedText;
    while ( textNode && (result = regex.exec(textNode.data)) ) {
        matchedTextNode = textNode.splitText(result.index);
        matchedText = result[0];
        matchLength = matchedText.length;
        textNode = (matchedTextNode.length > matchLength) ?
            matchedTextNode.splitText(matchLength) : null;
        surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
        parent.insertBefore(surroundingNode, matchedTextNode);
        parent.removeChild(matchedTextNode);
    }
}

var urlRegex = /http(s?):\/\/($|[^\s]+)/;

function replaceImageUrls(el) {
    surroundInElement(el, urlRegex, createImage);
}

<div id="s">One
    http://www.google.co.uk/images/logos/ps_logo2.png
    two
    http://www.google.co.uk/images/logos/ps_logo2.png three</div>

<input type="button" onclick="replaceImageUrls(document.getElementById('s'))" value="replace">
Answer

i might misunderstand your question. From what i understand, could use a div as a placeholder

//HTML
<p>
    <div id="holder"><a>link to image</a></div></p>

//js
var h = document.getElementById("holder");
if(h)h.innerHTML = "<img.....>" //the image tag

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.