Javascript 删除超链接但保留文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6188277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:38:30  来源:igfitidea点击:

Remove hyperlink but keep text?

javascriptjqueryhyperlink

提问by matt

<a href="http://www.website.com/something" title="Show Profile">Mentalist</a>

Whenever a hyperlink has a title of "Show Profile" I want to remove the hyperlink and replace it with only with the text.

每当超链接的标题为“显示个人资料”时,我想删除超链接并仅用文本替换它。

So instead of

所以代替

<a href="http://www.website.com/something" title="Show Profile">Mentalist</a>

I want to have only Mentalist.

我想要只有Mentalist.

Any idea how to solve that?

知道如何解决这个问题吗?

回答by DanielB

this should work:

这应该有效:

$('a[title="Show Profile"]').contents().unwrap();

Here a Fiddlewith the proof.

这是证明的小提琴

回答by rciq

This will do:

这将:

<a href="http://www.website.com/something" title="Show Profile">Mentalist</a>
<a href="http://www.website.com/something" title="Something Else">Mentalist</a>

<script type="text/javascript">
$("a[title='Show Profile']").each(function(){
    $(this).replaceWith($(this).text());
});
</script>

It should replace only the first link.

它应该只替换第一个链接。

回答by Prem

To do this on links of multiple classes,

要在多个类的链接上执行此操作,

$("a.className1, a.className2").contents().unwrap();

回答by Yuci

Vanilla JavaScript way (instead of jQuery) to remove hyperlink but keep text:

删除超链接但保留文本的香草 JavaScript 方式(而不是 jQuery):

const links = document.querySelectorAll('a[title="Show Profile"]')

links.forEach(link => {
    const el = document.createElement('span')
    el.textContent = link.textContent
    link.parentNode.replaceChild(el, link)
})