Satomi
Satomi

Reputation: 11

How to remove the <a> and </a> from <a>link</a>

How to remove the <a> and </a> from <a>link</a>? via JavaScript

Upvotes: 1

Views: 143

Answers (4)

James
James

Reputation: 22237

This function accepts any html element, takes all of its children (be they text nodes or other html elements) and appends them to the element's parent. Then it removes the element. Without jquery.

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

example of use

<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>

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185893

a.parentNode.replaceChild(document.createTextNode(a.textContent), a);

where a is the reference to that ANCHOR element.

Live demo: http://jsfiddle.net/simevidas/S79pZ/

Upvotes: 1

Zach
Zach

Reputation: 7930

Without jQuery:

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

Upvotes: 3

SLaks
SLaks

Reputation: 887315

You can use jQuery:

If it's a string:

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

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

htmlSource = tree.html();

If it's already in the DOM:

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

Upvotes: 0

Related Questions