1

I want to remove a colon at the end of my titles, so I use this:

$('.title').html($('.title').html().replace(':', ''))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
  Apples:
</div>
<div class="title">
  Oranges:
</div>

It works, it removes the colons, but it also replaces second title Oranges with Apples?

https://jsfiddle.net/X528L/8/

2 Answers 2

5

You can give html a closure and change each one independently of each other.

$('.title').html(function(index, currentHTML){
  return currentHTML.replace(/:/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
Apples:
</div>
<div class="title">
Oranges:
</div>

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

3 Comments

note that callback second argument also returns existing html
@charlietfl interesting. I'm not sure I've ever looked at the arguments for that before. Then again I hardly ever perform this kind of operation.
Same concept for text(function), val(function) etc
1

You're close. You're getting a collection because there are more than one element with title as class name. I would suggest iterating the element to replace the value.

$.each($('.title'), function(key, value) {
    $(value).html($(value).html().replace(':',''));
});

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.