3

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?

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • a cross browser solution is difficult for this unless you are in control of the code which creates the new elements... in that case you can modify the code to add this attribute.... else another solution is to have a look at mutation events/observers.. but IE support will be a problem – Arun P Johny Jan 26 '14 at 09:11
  • I suggest you add a listener to the
      since
    • will be added dynamically (or only one time on load?) , once they are being modified or being added to, then filter/select them all and apply your .attr function. Check this out -> (http://stackoverflow.com/questions/6209304/jquery-binding-a-single-event-listener-that-can-handle-events-of-its-children)
    – Mohammed Joraid Jan 26 '14 at 09:14
  • delegate/on only work on events, and the list of events could be happen on any element and any user-driven or non-user-driven events – Nick Ginanto Jan 26 '14 at 09:16

1 Answers1

2

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:

  1. Add the listener to body or parent div that holds the <ul> and monitor when <ul> is added then apply your attr.
  2. Add a 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..

Community
  • 1
  • 1
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38