1

Here is a div:

<div id="components-reconnect-modal" class="components-connecting-show">
  <div id="1">
  <div id="2">
  <div id="3">
  <div id="4">
</div>

The id will not change forever but the class will change by a third-party js library.

I need to get to know while the class of #components-reconnect-modal changes, according to the different classes show the different child div.

How can I achieve this?

Thank you.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Melon NG
  • 2,568
  • 6
  • 27
  • 52
  • Can you please elaborate more on your problem, like which class decide which div to show and will there be any possibility to have multiple classes? Have you tried anything on your end first? – Bhushan Kawadkar Dec 23 '19 at 13:06
  • 1
    u can see https://stackoverflow.com/q/19401633/6309457 – Devsi Odedra Dec 23 '19 at 13:07
  • @BhushanKawadkar Yes, there will be multiple classes there. That means it may display multi-child div. – Melon NG Dec 23 '19 at 13:18

3 Answers3

1

You have to listen to the changes made in the element. You can try with MutationObserver

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.

Demo:

// Listen to the changes in the header element and add row
var target = document.querySelector('#components-reconnect-modal');

setTimeout(function() {
  target.className = "myClass"; // change class after 2 seconds
}, 2000)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('New class is: ' +target.getAttribute('class'));
  });
});

var config = {
  attributes: true,
  childList: true,
  characterData: true
};

observer.observe(target, config);

// otherwise
observer.disconnect();
observer.observe(target, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="components-reconnect-modal" class="components-connecting-show">
  <div id="1">
  <div id="2">
  <div id="3">
  <div id="4">
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

I believe MutationObserver is what you're looking for.

Here is a relevant SO question on the matter that uses JQuery.

Basically, the MutationObserver interface provides the ability to watch for changes being made to the DOM tree, I believe you'll find more information in both of the links I attached.

guychouk
  • 671
  • 1
  • 8
  • 28
0

You can use any of the following ways:
1. If the element is being added before the DOM is ready, you can do this:

$(document).ready(function () {
   if($('.list li').hasClass('aDynamicallyGeneratedClass')){
     //Then do this with my object.
   });
});

2.You need to make your function run at an interval after the page has loaded.

function checkClass() {
$('#test').hasClass('complete');
}
checkClass();
setInterval(checkClass, 60*1000);
Nivin John
  • 173
  • 1
  • 11