Search code examples
javascriptjquerydommutation-observers

Add attribute to all newly created elements


For example add to all new links attribute target with value _blank or to all new <div>s attribute title with random value. Any ideas except setTimout()?

UPD: I need something like .attrGlobal(). This answer allows to do that only with links and their attribute target, but how to do that with all elements and all their attributes?

UPD2: Trying MutationObserver as SLaks recommended but firefox freezes when clicking on add button http://jsfiddle.net/1337/wvfkc/5/.


Solution

  • Finally found solution.

    MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
    
    var observer = new MutationObserver(function() {
      $("a").attr("target", "_blank");
      $("div").attr("title", Math.floor(Math.random() * 1000));
    });
    
    observer.observe(document, {
      subtree: true,
      childList: true
    });
    

    jsfiddle.net

    In options you need subtree: true always, and if you changes attributes do not add to options attributes: true because MutationObserver(function(mutations, observer) { will go into the eternal cycle and browser freezes.