AlexGH AlexGH - 1 year ago 73
HTML Question

jQuery replaceWith() not working correctly when using indexOf()

What's wrong with this code? I want to replace one

by another one according to the condition...

jQuery (I think that the main problem is inside the if condition, maybe it's not recognizing the

$(document).ready() {
$("#firstdiv img").replaceWith(function () {
if(this.src.IndexOf("soccer2") > -1) {
return $("<img src='/images/soccer ball.jpg'/>")


<div id="firstdiv" class="divvv">
<img src="/images/Soccer.jpg" width="60" height="60" alt="soccer icon" />
<img src="/images/soccer2.jpg" alt="soccer icon" width="60" height="60" />

Answer Source

You have type in IndexOf. It should be : indexOf