Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove all HTML tags EXCEPT Anchors

Tags:

html

jquery

Currently, I have this line:

this.html(this.html().replace(/\x3C\x2F?[^\x3E]+\x3E/gi, ''));

But, I would like something along the lines of an "if clause" to say,

IF (this.tag = "<a") {
  do nothing
} ELSE {
  remove tag
}

I don't suppose anyone has any ideas?

[EDIT]: I think I may have to do a "FOR EACH" loop... I think.... [/EDIT]

^.^

like image 335
Barrie Reader Avatar asked Jun 03 '26 10:06

Barrie Reader


2 Answers

jQuery has ":not" pseudo-selector.

$(':not(a)', this).remove()
like image 156
migajek Avatar answered Jun 06 '26 00:06

migajek


this.html(this.html().replace(/<\/?([b-z]+)[^>]*>/gi, function(match, tag) { 
  return (tag === "a") ? match : ""; 
})); 

If you are looking at leaving the "a" tags in place, change the regular expression from [a-z] to [b-z]

like image 43
Neil Knight Avatar answered Jun 06 '26 01:06

Neil Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!