Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect when an HTML element’s class changes? [duplicate]

<div class="current"></div>
<a href="#">text</a>

How do I detect when e.g. a .live class is added to this <div> and do something when it happened?

For example, if class is changed, then hide the link.

I have a minified script that makes changes on the <div>'s class. It’s too big for me to find the place where it happens, so I'm searching for some way to catch the class change.

like image 765
James Avatar asked May 17 '11 16:05

James


People also ask

Can two elements have same class in HTML?

The HTML class attribute is used to specify a class for an HTML element. Multiple HTML elements can share the same class.

Can class be repeated in HTML?

Yes, it is possible, but you can only declare the class attribute once per HTML element. Just separate the classes you want to apply by a space.

Can two tags have same class?

Using same class in different tags: Different tags, like <h2> and <p>, can have the same class name and thereby share the same style. Example: HTML.

How do you listen to a class change?

To listen to class change we need to instantiate the MutationObserver object, pass the callback function, and call the observe() method. The observe() method accepts two arguments the target node and options object which should contain attributes property that is set to true.


1 Answers

There are DOM events, but they are far from perfect and not available in most browsers. In other words: Not possible (reliably). There are hacks like intervals and checking it in each iteration, but if you need to do something like this, your design is probably screwed. Keep in mind that such things will be slow and that there will always be a delay. The smaller the delay, the slower the application. Do not do that.

like image 51
jwueller Avatar answered Oct 08 '22 10:10

jwueller