0

I have a <ul> element on my page with a few children. A class attribute will be added to these children at some point,

Before

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

After

<ul>
  <li class='classname'>1</li>
  <li>2</li>
  <li>3</li>
</ul>

I would like to bind to an event that will fire whenever the li element's class changes, so I can handle it accordingly. Is there such an event?

Andy E
  • 338,112
  • 86
  • 474
  • 445

3 Answers3

2

I believe that there is some way to bind to a DOM Mutation event, but I've never actually done this myself, and don't know even if it's supported cross-browser.

Instead, just find the code which actually makes the change and insert your handler there.

function something() {
    $('li').addClass('classname');
    doSomething(); // <-- here
}

Or, if you want to be able to break it apart and use events, you can trigger custom events with jQuery.

function something() {
    $('li').addClass('classname').trigger('classChange');
}

// elsewhere:
$('li').bind('classChange', function () { ... });
nickf
  • 537,072
  • 198
  • 649
  • 721
  • All - Just a note: [DOM mutation events](https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent) were deprecated fairly soon after this answer was written in 2011. Instead, see the answers to [this question](https://stackoverflow.com/questions/10612024/event-trigger-on-a-class-change) -- basically, use a [mutation observer](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). – T.J. Crowder Oct 07 '22 at 08:15
0

I Think you need to see this post

jQuery - Fire event if CSS class changed

rather i hate jquery and i will search it on pure javascript

Regards

Community
  • 1
  • 1
Marwan
  • 2,362
  • 1
  • 20
  • 35
  • 1
    You haven't done any big projects yet, this is why you'd never had to use jQuery. – Hossein Nov 28 '11 at 09:20
  • 1
    @ Hossein i did many big projects and for each i use my own framework mScript and from time to time i add new features to my framework from my new experience // i only use jquery when i'm in too tight schedule and i face new issues not covered in my framework – Marwan Nov 28 '11 at 09:34
0

Depending on how you are going to change the elements, you can use custom events and custom getters to simulate a 'real' event.

Viruzzo
  • 3,025
  • 13
  • 13