2010-10-28 64 views
3

想,我有這樣的一段話:DOM包裹在textnode一個子一個新跨越節點

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

我想和圖像元素來取代http://lol/atme.png。 我該怎麼做? 它像刪除文本,但添加一個圖像元素,而不是該文本。

幫助將不勝感激。

+0

目前尚不清楚爲什麼你需要的XPath ... – 2010-10-28 16:42:58

回答

3

有兩個環節進行。首先是從文本中提取URL,這是一個我不感興趣的棘手問題。在使用這個產品之前,我會做一些研究。現在,我將使用一個非常簡單的說明性正則表達式。

第二部分是在文本節點內進行替換的代碼。我answered a related question與一些可重用的代碼,現在我正在重新使用它。好極了。

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"> 
+0

是不是說,而是一個很長的路要走:'(E = document.getElementsByClassName( 'PLN')[0])的innerHTML = e.innerHTML .replace(/ [az] {3,}:\/\/[^ \ s] +/g,function(s){return }}(你可以在控制檯中運行它,btw) – Orwellophile 2015-04-25 21:47:52

+0

@ Orwellophile:我想在這種情況下,只要你處理的是沒有嵌套元素的單個元素。 – 2015-04-26 15:56:33

0

我可能會誤解你的問題。 從我個人理解,可以使用一個div作爲佔位符

//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 
相關問題