0

So I have this table below. And I want to get the text inside td.am-receipt-price but without getting the span text included.

<table>
  <tbody>
    <tr>
      <td class="am-receipt-price">
        <span class="am-receipt-discounted-price"><del>price 1</del></span>
        price 2
      </td>
    </tr>
  </tbody>
</table>

console.log ( $(".am-receipt-price").text() ) would also return the text inside the span. I have tried .remove("span") but it wont work.

Am I missing any selector that I have not tried yet? thanks in advance.

1
  • Agree with @Drdilyor, it looks like the accepted answer to the question they linked should work pretty well for your case Commented Jun 4, 2021 at 11:46

2 Answers 2

3

The simplest solution would be to add another element around the target node and use a selector to retrieve it.

Assuming you cannot amend the HTML, then you can use contents() and filter() on the parent td to target the node and read its textContent.

let $td = $('.am-receipt-price');
let nodes = $td.contents().filter((i, n) => n.nodeType === Node.TEXT_NODE && n.textContent.trim() !== '');

console.log(nodes[0].textContent.trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="am-receipt-price">
        <span class="am-receipt-discounted-price">
          <del>price 1</del>
        </span> 
        price 2
      </td>
    </tr>
  </tbody>
</table>

Sign up to request clarification or add additional context in comments.

1 Comment

I also found that this script also works $(this) .clone() .children() .remove() .end() .text();
0

An alternative to the already provided .contents() solution (if you need/want an alternative) is to use .clone() and .remove(), where you copy the html into a variable then you can do what you want with it without changing the original.

var price = $("td.am-receipt-price").clone();
price.find("span").remove();
console.log(price.text().trim())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="am-receipt-price">
        <span class="am-receipt-discounted-price">
          <del>price 1</del>
        </span> 
        price 2
      </td>
    </tr>
  </tbody>
</table>

It may be that your .remove("span") just had the wrong syntax:

$("td.am-receipt-price").find("span").remove()

would change the original DOM nodes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.