我有一些表格数据,如下所示:
<td class="homebranch">
This is some Text!
<span class="location">Texas</span>
</td>
我如何使用jQuery删除文本(这是一些文本)但保留span类?
您可以将html设置为应保留的元素。
$(".homebranch").each(function() {
$(this).html($(".location", this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="homebranch">
This is some Text!
<span class="location">Texas</span>
</td>
</tr>
<tr>
<td class="homebranch">
This is some Text!
<span class="location">Another Texas</span>
</td>
</tr>
<table>
您需要访问作为td
的第一个子节点的文本节点,并将nodeValue
设置为""
。为此,您必须通过将td
传递给集合来从JQuery包装集中提取[0]
。这将返回一个常规DOM节点,然后您可以调用firstChild
来获取文本节点。
$("td.homebranch")[0].firstChild.nodeValue = "";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="homebranch">
This is some Text!
<span class="location">Texas</span>
</td>
</tr>
<table>