如何使用Javascript / Jquery用一个div元素替换HTML中的所有链接?

时间:2013-06-27 16:17:10

标签: javascript jquery

如何用一个div元素替换HTML中的所有链接?

例如:我的链接代码为:

<div class="link"><a href="stackoverflow.com">Stackoverflow</a></div>
<div class="link1"><a href="stackoverflow.com/link1">Stackoverflow</a></div>

我现在想要替换为:

<div class="link">replaced link</div>
<div class="link1">replaced link</div>

我需要你的帮助。非常感谢。

4 个答案:

答案 0 :(得分:3)

这样做 -

$('a').replaceWith('replaced link');

演示---> http://jsfiddle.net/Txmrx/5/

答案 1 :(得分:1)

我认为您想要使用比您所讨论的示例更有意义的链接href:

$('a').replaceWith(function () {
    return '<div>'+$(this).attr('href')+'</div>';
});

答案 2 :(得分:1)

var as = document.getElementsByTagName('a');
while(as[0]){
  as[0].parentNode.replaceChild(document.createTextNode('replaced link'), as[0]);
}

答案 3 :(得分:1)

很抱歉,如果我不清楚读你的问题,如果你想改变div内容

$(function () {
var _newLink = [{
    href: 'newlink.com',
    title: 'New Link Title 1'
}, {
    href: 'newlink.com/link2',
    title: 'New Link Title 2'
}];

$('div[class*=link]').each(function (i) {
    var _divContent = '<a href="' + _newLink[i].href + '">' + _newLink[i].title + '</a>';

    $(this).html(_divContent);
});

});

here my demo