9

For sure this question is very easy, but I just cannot figure this out.

I'm using DOMNodeInserted event to detect when a new element is inserted.

I don't know how to use the current element, for example to get it's parent id.

Now I have the function like this:

document.addEventListener("DOMNodeInserted", function(event){
  var element = event.target;

  if (element.tagName == 'DIV') {
    if (element.id == 'ndiv_3-1VTSTHR') {
     alert($('#ndiv_3-1VTSTHR').parent().get(0).tagName);
    }
  }
});

This works, but it will give me the parent to ndiv_3-1VTSTHR element. I want to know the parent to any element, using jQuery.

I tried with:

alert($(this).parent().get(0).tagName);

but with no luck.

2
  • What about removing the if for filtering a specific id? And then use $(element). Commented Jul 25, 2011 at 9:43
  • @pimvdb: Nope, tried with alert($(element).tagName); and is giving me undefined. Commented Jul 25, 2011 at 9:49

1 Answer 1

10

You probably need to initialize a jQuery object around element.target. Try:

document.addEventListener("DOMNodeInserted", function(event) {
    alert($(event.target).parent()[0].tagName);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Either element or event.target I think :)
Thanks, this works. But if I make var el = $(event.target).parent()[0]; can I use it further with alert($(el).tagName)?
@Parkyprg, tagName is a property exposed by DOM elements, not jQuery objects. You'd have to write either el.tagName or $(el)[0].tagName. It might be best to store the jQuery object itself in el: var el = $(event.target).parent();. From there you can do el[0].tagName to obtain the element's tag name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.