Quantcast
Channel: What's the best way to strip out only the anchor HTML tags in javascript, given a string of html? - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by eyelidlessness for What's the best way to strip out only the anchor HTML tags in javascript, given a string of html?

$
0
0

This approach will preserve existing DOM nodes, minimizing side-effects if you have elements within the anchors that have events attached to them.

function unwrapAnchors() {    if(!('tagName' in this) || this.tagName.toLowerCase() != 'a' || !('parentNode' in this)) {        return;    }    var childNodes = this.childNodes || [], children = [], child;    // Convert childNodes collection to array    for(var i = 0, childNodes = this.childNodes || []; i < childNodes.length; i++) {        children[i] = childNodes[i];    }    // Move children outside element    for(i = 0; i < children.length; i++) {        child = children[i];        if(('tagName' in child) && child.tagName.toLowerCase() == 'a') {            child.parentNode.removeChild(child);        } else {            this.parentNode.insertBefore(child, this);        }    }    // Remove now-empty anchor    this.parentNode.removeChild(this);}

To use (with jQuery):

$('a').each(unwrapAnchors);

To use (without jQuery):

var a = document.getElementsByTagName('a');while(a.length) {    unwrapAnchors.call(a[a.length - 1]);}

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>