如何从文本中删除具有特定类的所有DOM元素?
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>";
答案 0 :(得分:1)
您可以将HTML转换为DOM对象,删除指定的项目并恢复其HTML:
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>
答案 1 :(得分:0)
更好的方法是首先将html字符串解析为DOM,然后使用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