我想通过使用jQuery在字符串中使用html结构。但是这个字符串中有一个元素必须被删除(表格)。 我有这个HTML结构:
<body>
<div>
<p>Some Text</p>
<p>More Text</p>
<table>
... i don't need this table
<table>
<p>last Text</p>
</div>
</body>
这是我的js:
var content = $("body > div");
content = $(content).html();
现在我还想要除了table-element
之外的字符串中的html结构结果应为:
content = "<p>Some Text</p><p>More Text</p><p>last Text</p>";
它是如何运作的?
答案 0 :(得分:1)
要实现这一目标,您只需find()
选择中的table
和remove()
,就像这样:
var $content = $("body > div").clone();
$content.find('table').remove();
var content = $content.html();
console.log(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<p>Some Text</p>
<p>More Text</p>
<table>
<tr>
<td>... i don't need this table</td>
</tr>
</table>
<p>last Text</p>
</div>
</body>
答案 1 :(得分:1)
如果您想获取HTML,请忽略<table>
,但不删除它:
let html = $('body > div > :not(table)').get().map(el => el.outerHTML).join('');
这将获得所有不是<table>
的元素,提取outerHTML然后加入所有内容。