1

I am trying to change the text value of an element if another element has a class but what I am currently doing is showing no results.

$(document).ready(function () {
    $('#number').text('00');

    setTimeout(function () {
        $('#test').removeClass('initial-number').addClass('change-number');
    }, 500);
});

$(document).change(function () {
    if ($('#test').hasClass('change-number') === true) {
        $('#number').text('10');
    };
});
#test {
  height: 2em;
  width: 2em;
}

.initial-number {
  background: blue;
}

.change-number {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="number"></span>
<div class="initial-number" id="test"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95
  • possible duplicate of [JQuery does not execute on $(document).change()](http://stackoverflow.com/questions/12495128/jquery-does-not-execute-on-document-change) – renakre May 12 '15 at 12:58

4 Answers4

4

document has no change event; that's only for form field elements.

You can use mutation observers for this, watching for changes to the attributes of the element in question. They're well-supported on modern browsers; on slightly less-modern browsers, you can find a polyfill using the old mutation events. On really older browsers, you'll have to poll.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Try this

   $(document).ready(function () {
$('#number').text('00');

setTimeout(function(){
  $('#test').removeClass('initial-number').addClass('change-number');
   $('#number').text('10');
  }, 500);
});


  
#test {
  height: 2em;
  width: 2em;
}

.initial-number {
  background: blue;
}

.change-number {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="number"></span>
<div class="initial-number" id="test"></div>
Asim Shaikh
  • 159
  • 9
1

Why not simply include it in the setTimeout function:

$(document).ready(function () {
    $('#number').text('00');

    setTimeout(function () {
        $('#test').removeClass('initial-number').addClass('change-number');
        if ($('#test').hasClass('change-number')) {
            $('#number').text('10');
        };
    }, 500);
});
Julien Grégoire
  • 16,864
  • 4
  • 32
  • 57
0

try this

 $(document).bind('DOMSubtreeModified', function () {
       if ($('#test').hasClass('change-number') === true) {
        $('#number').text('10');
      };
    });

Change is only for input, textarea or select elements.

Gurgen Sargsyan
  • 1,087
  • 15
  • 22