2011-04-13 94 views
1

刪除如何刪除<a>link</a><a></a>?通過JavaScript如何從<a>鏈接</a>

+6

可能重複http://stackoverflow.com/questions/1369816/remove-tag-around-a- text-node-using-javascript) – Neal 2011-04-13 17:38:39

+0

它是一個字符串還是一個DOM元素? – SLaks 2011-04-13 17:39:16

+0

你使用像[jQuery](http://jquery.com/)這樣的框架嗎?或者只是純javascript? – Marnix 2011-04-13 17:39:18

回答

0

You can use jQuery

如果它是一個字符串:

var htmlSource = ...; 
var tree = $("<div>" + htmlSource + "</div>"); 

tree.find('a[href]') 
    .replaceWith(function() { return this.childNodes }); 

htmlSource = tree.html(); 

如果它已經存在於DOM:

$(...).find('a[href]') 
     .replaceWith(function() { return this.childNodes }); 
3

沒有jQuery的:

function GetInnerContents() { 
    var tempElem = document.createElement("div"); 
    tempElem.innerHTML = "<a>link</a>"; 
    var aTag = tempElem.firstChild; 
    return aTag.innerHTML; 
} 
0

這個函數接受任何HTML元素,需要所有的孩子(無論是文本節點或其他HTML元素),並追加到元素的父。然後它刪除元素。沒有jQuery。

function removeAnchor(tag) { 
    while (tag.childNodes.length > 0) 
    tag.parentNode.insertBefore(tag.childNodes[0], tag); 
    tag.parentNode.removeChild(tag); 
} 

使用的示例

<a href='dontcare' id='myanchor'>Click me <img src='http://www.google.com/images/logos/ps_logo2.png'> Thanks </a> 
<script> 
removeAnchor(document.getElementById('myanchor')); 
</script> 
的[圍繞文本節點使用JavaScript移除標籤(