Approach #1 - Remove all the 'a' tags while retaining their content - no way to retrieve the links, etc.
This lets you effectively disable all the links without losing any text. Using the .html() call instead of simply .text() means that any images or other formatting is preserved.
$("a").each(function() {
var t = $(this).html();
$(this).replaceWith(t);
});
Approach #2 - Reversibly Hide and Show the tags
Replace the 'a' tags with 'span' tags and store the original tag pair in a custom data attribute
Custom data attributes all have the prefix 'data-' followed by a unique name. You can store arbitrary data in these. With this approach I am storing the original 'a' tag pair and its contents.
In the example, my custom data attribute is called 'data-craic' and note that the 'span' tags are given a unique class (I'm using 'hidden-link') that allows you to identify them
To hide/disable the links:
$("a").each(function() {
// Get the html within the 'a' tag pair
var t = $(this).html();
// Get the entire tag pair as text by wrapping in an in-memory 'p' tag and fetching its html
var original_tag = $(this).clone().wrap('<p>').parent().html();
// Replace the 'a' tag with a 'span' - put the original tag in the data attribute
$(this).replaceWith("<span class='hidden-link' data-craic='" + original_tag + "'>" + t + "</span>");
});
To show/enable the links:
$(".hidden-link").each(function() {
// Retrieve the original tag from the data attribute
var original_tag = this.dataset.craic;
// Replace the 'span' with it
$(this).replaceWith(original_tag);
});
At least in my use cases I have not had to encode the original 'a' tag pairs but base64 encoding might be a good idea to avoid any possible unintended consequences.
Custom data attributes are extremely useful and were the perfect to solution to this problem
You can find a self contained web page with these scripts at https://gist.github.com/craic/4987192