Reputation: 32190
I need to add dir=auto
to several ul
element that are being added dynamically when several events happen.
Since these events are not in my control (some are plug-ins, some are ajax results, etc) I don't want to add a line of code sporadically
how can I add $("ul").attr("dir","auto")
in a way that any of the relevant elements will have the attributes once they are added to page?
Upvotes: 3
Views: 2828
Reputation: 6490
If I understand you correctly, you need to add a listener to the document/dom to know once the<ul>
has been added dynamically, then check if that <ul>
has been modified as well later after load (to add other attri to them?).
The listener should work once <ul>
is being modified or being added to the document, then filter/select the <ul>
and apply your .attr
function. Check this and this
I've tested the code on my console for this SO page and it seems to be working. I'm using FF26, therefore something like this might help:
//listen to parent to know if it's being modified. you can listen to <ul> if you want to check if it has modified if you want to do something with <li> for example.
$("#parentDiv").bind("DOMSubtreeModified", function() {
//your code here
$("ul").attr("dir","auto");// to all <ul> in the page
//or only filter ul that belongs to this div
// this.find("ul").attr("dir","auto");
});
I think this answer has more accurate findings since (DOMSubtreeModified
) seems to be deprecated (although it just worked fine).
If the <ul>
is going to be added later (unknown time) then in my opinion, you have two options:
body
or parent div that holds the <ul>
and monitor when <ul>
is added then apply your attr. setInterval
to keep checking if there is any <ul>
in the page every a few sec?I prefer option 1, because I've read that option 2 (using setInterval
) might add some overhead. Ref..
Upvotes: 2