Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  118] [ 5]  / answers: 1 / hits: 22344  / 7 Years ago, sun, july 23, 2017, 12:00:00

I have the following string variable and I want to remove all a tags with its content from the string.



var myString = <table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>;
myString += <table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>;
myString += <table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>;


I have checked this Remove HTML content groups from start to end of string in JavaScript question's answers but it is for all tags.



Thank you


More From » html

 Answers
68

You should avoid parsing HTML using regex. Here is a way of removing all the <a> tags using DOM:





// your HTML text
var myString = '<table><tr><td>Some text ...<a href=#>label...</a></td></tr></table>';
myString += '<table><tr><td>Some text ...<a href=#>label...</a></td></tr></table>'
myString += '<table><tr><td>Some text ...<a href=#>label...</a></td></tr></table>'

// create a new dov container
var div = document.createElement('div');

// assing your HTML to div's innerHTML
div.innerHTML = myString;

// get all <a> elements from div
var elements = div.getElementsByTagName('a');

// remove all <a> elements
while (elements[0])
elements[0].parentNode.removeChild(elements[0])

// get div's innerHTML into a new variable
var repl = div.innerHTML;

// display it
console.log(repl)

/*
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
*/




[#56998] Thursday, July 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
michelecarissab

Total Points: 730
Total Questions: 97
Total Answers: 110

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
;