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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CristiC
  • 22,068
  • 12
  • 57
  • 89

1 Answers1

10

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

document.addEventListener("DOMNodeInserted", function(event) {
    alert($(event.target).parent()[0].tagName);
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • Either `element` or `event.target` I think :) – pimvdb Jul 25 '11 at 09:50
  • Thanks, this works. But if I make var el = $(event.target).parent()[0]; can I use it further with alert($(el).tagName)? – CristiC Jul 25 '11 at 09:52
  • @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. – Frédéric Hamidi Jul 25 '11 at 09:53