Drake
Drake

Reputation: 165

Remove all elements with specific class from text

How to remove all DOM elements with specific class from text?

var html = "<table>"+
"<tr>"+
"<td>1</td>"+
"<td>2</td>"+
"<td class='del'>3</td>"+
"</tr>"+
"<tr>"+
"<td>1</td>"+
"<td>2</td>"+
"<td class='del'>3</td>"+
"</tr>"+
"</table>";

Upvotes: 2

Views: 1582

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can convert HTML to DOM objects, remove specified items, and get its HTML back:

var html = "<table>" +
    "<tr>" +
    "<td>1</td>" +
    "<td>2</td>" +
    "<td class='del'>3</td>" +
    "</tr>" +
    "<tr>" +
    "<td>1</td>" +
    "<td>2</td>" +
    "<td class='del'>3</td>" +
    "</tr>" +
    "</table>";

var $obj = $(html); // Create jQuery object
$obj.find(".del").remove(); // Remove .del items
var htmlNew = $obj[0].outerHTML; // Get the updated HTML
 
// Demonstration purposes only:
$("body").text(htmlNew);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Nishad K Ahamed
Nishad K Ahamed

Reputation: 1394

Better way is to first parse the html string as DOM, then remove specific children using classname

var htmlString = "html string"
var parser = new DOMParser()
var doc = parser.parseFromString(htmlString, "text/xml");

$(doc).find('className').remove()//remove specific elements

var filteredHtml=$(doc).html()//get the new html string after removing the elements

Upvotes: 0

Related Questions