简体   繁体   中英

Convert hyperlinks to plain text using JavaScript

Using JavaScript, is it possible to convert a hyperlink to plain text (so that it no longer links to any page?)

For example, would it be possible to change the following link (inside the <a> tag) to plain text using JavaScript (so that this text no longer links to any page)?

<html>
    <body>
        <a href="http://www.wikipedia.org/" target="blank" id = "wikiLink">Go to Wikipedia</a>
    </body>
</html>

The simplest way would be to remove its href attribute:

document.getElementById('wikiLink').removeAttribute("href");

If you want to completely remove the node, leaving the text, try this:

var toRemove = document.getElementById('wikiLink'), parent = toRemove.parentNode,
    text = toRemove.firstChild;
parent.insertBefore(text,toRemove);
parent.removeChild(toRemove);
parent.normalize();
document.getElementById("wikiLink").removeAttribute('href')

或与jQuery

$("#wikiLink").removeAttr('href');

Following code should render hyper link as text.

$(element).find('a').contents().unwrap();

JS BIN Demo

If you want to remove the "link" behavior of all links, you can do:

var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++) links[i].href = '';

With jQuery a simple way is to remove the link and to put a text node instead:

var $link = $('#wikiLink');
$link.after($link.text());
$link.remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM