3

In my page I change one attribute of an element based on another attribute. Like this:

$("body").find("[data-action=new]").attr("data-original-title", "Create appointment"); 

Doing that, this element will display a tooltip with "Create appointment" text.

Like this I have any others.

The problem begin when I insert some elements via JS in my DOM.

There is any way to delegate this operation to avoid calling this every time I insert one element?

Update

I'm looking for a simple solution to setup my tooltips. The DOMObserver looks too heavy for use here. Or not?

8
  • The only things I can think of would be to setup a MutationObserver and let that handle the inserting of the attributes, or create a custom event and trigger it on insert. Not sure if either of those is any better though. Commented Jun 11, 2015 at 16:52
  • Interesting related posts here and here. Might provide some helpful ideas. Commented Jun 11, 2015 at 16:52
  • 1
    possible duplicate of Most efficient method of detecting/monitoring DOM changes? Commented Jun 11, 2015 at 16:58
  • 2
    @Scott'scm6079' it also refers to plain javascript approach too not just jquery.. plenty of answers are available on that post.. Commented Jun 11, 2015 at 17:02
  • 1
    I looked through the post again, I still don't think that post answers this at all -- I've taken the time to writeup a solution that does answer the need. Commented Jun 11, 2015 at 17:09

1 Answer 1

1

A mutation observer seems appropriate, monitoring the addedNodes property:

var targetNodes = $("body"); // best to make this more specific, e.g. .myNodes var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var myObserver = new MutationObserver (mutationHandler); var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true }; targetNodes.each ( function () { myObserver.observe (this, obsConfig); } ); function mutationHandler (mutationRecords) { mutationRecords.forEach ( function (mutation) { if (typeof mutation.addedNodes == "object") { var jq = $(mutation.addedNodes); jq.find("[data-action=new]").attr("data-original-title", "Create appointment"); } } ); } 
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, but I expect you'll need a fallback for IE < 11
@dave Good point - this solution works in Chrome, Safari, IE11+. caniuse.com/#feat=mutationobserver
Will this not cause a loop, because it will be changing the DOM again ?
In this case, they won't be added nodes - so it should be fine. However for people using this post for related items that's a great point. It would be easy to exclude changes by putting it in the inner find's selector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.