Wait until HTML elements gets a class then do something

岁酱吖の 提交于 2021-02-06 10:55:44

问题


I am waiting for the document.ready event in order to do something on my page.

Alas some other script, which I cannot change, has not worked its magic yet once my script is called. Hence, jquery selection on the class name fails as the class does not yet exist in the DOM.

This is why I want tell my function to listen until an element gets a certain class, then do something with it.

How do I achieve this?


回答1:


You could trigger some event once you added the class.

Example:

$('#ele').addClass('theClass');
$(document).trigger('classGiven')


$(document).bind('classGiven',function(){
    //do what you need
});



回答2:


Something like this (pseudo code) :

var timer = setInterval(function() {
   if (element.className=='someclass') {
       //run some other function 
       goDoMyStuff();
       clearInterval(timer);
   }
}, 200);

or listen for the element to be inserted:

function flagInsertedElement(event) {
   var el=event.target;
}
document.addEventListener('DOMNodeInserted', flagInsertedElement, false);

jQuery version:

$(document).on('DOMNodeInserted', function(e) {
    if (e.target.className=='someclass') { 
        goDoMyStuff();
    }
});

There's also the liveQuery plugin:

$("#future_element").livequery(function(){
    //element created
});

Or if this is a regular event handler, delegated events with jQuery's on();




回答3:


I'm sorry if I got your question wrong but why not just doing something plain as this on document.ready ? :

$("#myelement").addClass('myclass');

if($("#myelement").hasClass('myclass')) {
    alert('do stuff here');
}


来源:https://stackoverflow.com/questions/10334838/wait-until-html-elements-gets-a-class-then-do-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!