47

With text like this:

<div class="element">
<span>N/A, Category</span>
</div>

I want to get rid of every occurrence of N/A.

Here is my attempt:

$('.element span').each(function() {
        console.log($(this).text());
        $(this).text().replace('N/A, ', '');
    });

The logged text is the text inside of the span so the selector is okay.

What am I doing wrong here?

1
  • 1
    replace returns a string, it does not perform in place changes. And even then, the text would be set to the element automatically. Commented May 30, 2011 at 13:58

2 Answers 2

105

You need to set the text after the replace call:

$('.element span').each(function() {
  console.log($(this).text());
  var text = $(this).text().replace('N/A, ', '');
  $(this).text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">
  <span>N/A, Category</span>
</div>


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});
Sign up to request clarification or add additional context in comments.

5 Comments

Or pass a function: $(this).text(function(i, text) { return text.replace(...);});
@Felix: Good call, I always forget about that version.
+1 for the second version, upvote one of @Felix 's answers to transfer it to him :).
@bazmegakapa: Haha, yep. I've given @Felix plenty of upvotes already :)
@Andrew I guess most of us have :).
14

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.