-1

Basicially I have 4 divs with the same class names. If the text from "option2" change to e.g "newoption" how can I add a class to the matching div?

<div class="htmlchange">option1</div>
<div class="htmlchange">option2</div>
<div class="htmlchange">option3</div>

Example:

<div class="htmlchange">option1</div>
<div class="htmlchange addclass">newoption</div>
<div class="htmlchange">option3</div>
Alexander Hein
  • 960
  • 3
  • 19
  • 44

3 Answers3

1

if you are changing the html of those htmlchange div with JS you can simply add your class to that element right there. Or based on this article you can spy on Document DOM tree https://davidwalsh.name/dom-events-javascript
Otherwise change event does not trigger for div .This event is limited to <input> elements, <textarea> boxes and <select> elements .

Here is an example http://jsfiddle.net/tg5op333/31/
HTML

<div class="htmlchange">option1</div>
<div class="htmlchange" id="2">option2</div>
<div class="htmlchange">option3</div>
<input type="button" id="change" value="change">

JS:

$('.htmlchange').bind("DOMSubtreeModified",function(){
 $(this).addClass('changed');
});

$("#change").click(function(){
    $("#2").html('changed');
  //you can either add from here or use  DOMSubtreeModified handler above   
  $("#2").addClass('changed');
})
Matin Kajabadi
  • 3,414
  • 1
  • 17
  • 21
0

Bind to a custom event

 $(".htmlchange").click(function() {
      $(this).trigger('contentchanged');
    });


    $(document).on('contentchanged', '.htmlchange', function() {
      // do something after the div content has changed
      $(this).addClass('test');
    });
santosh singh
  • 27,666
  • 26
  • 83
  • 129
0
<div class="htmlchange">option1</div>
<div class="htmlchange">option2</div>
<div class="htmlchange">option3</div>

Javascript which includes JQuery

$(".htmlchange").bind('DOMNodeInserted DOMNodeRemoved', function() {
$(this).addClass('someotherclass');
});

$("div.htmlchange").each(function (docindex) {
    if (docindex==1)
    {
         $(this).text("someotherclass");
     }
});

JSFiddle

And the last part I added in javascript is only for the demo purpose to change the content in option 2

$("div.htmlchange").each(function (docindex) {
if (docindex==1)
{
$(this).text("someotherclass");
}
});

Hope this helps!!! Happy Coding!!!!

Nirav Mehta
  • 6,943
  • 9
  • 42
  • 51