jquery从表中删除一些文本

问题描述 投票:-4回答:2

我有一些表格数据,如下所示:

<td class="homebranch">
  This is some Text!
  <span class="location">Texas</span>
</td>

我如何使用jQuery删除文本(这是一些文本)但保留span类?

javascript jquery html
2个回答
1
投票

您可以将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>

1
投票

您需要访问作为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>
© www.soinside.com 2019 - 2024. All rights reserved.