user3108268
user3108268

Reputation: 1083

Remove string from HTML for multiple elements

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/

Upvotes: 1

Views: 142

Answers (2)

Dorado
Dorado

Reputation: 431

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(':',''));
});

Upvotes: 1

Taplar
Taplar

Reputation: 24965

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>

Upvotes: 5

Related Questions