0

I have a problem understanding what is wrong here. I use jQuery to find an element, but I fail finding the element's parent without using jQuery:

$(".selectbox").on("click", function(e) {
   e = e || window.event;
   var eTarget = e.target || e.srcElement;
   find_parent(eTarget);
});

using above to call find_parent function works:

function find_parent (el) {
   element_parent = el.parentElement;
}

but if use this to call find_parent it fails:

function someFunction {
   selectBoxEl = $(".xyz").find('.selectbox');
   find_parent (selectBoxEl);
}

I am not looking for the solution of "why not using jQuery parent()" - and it works fine. I am trying to understand why normal DOM methods don't work on an element returned by jQuery and what I am doing wrong.

Edit: Sample code above is not the actual code being used, but a very simplified version to illustrate my question. The actual find_parent() function is a long and complicated piece that goes through many elements and their parents for various updates and it doesn't use jQuery. I want to leverage that code and not duplicating it for my need in the sample function someFunction().

Rasul
  • 223
  • 1
  • 2
  • 12
  • 1
    you have typo... there should not be space in between methodcall and round braces `find_parent(selectBoxEl);` – Milind Anantwar May 18 '15 at 11:19
  • possible duplicate of [jQuery object and DOM element](http://stackoverflow.com/questions/6974582/jquery-object-and-dom-element) – Mihai Matei May 18 '15 at 11:20
  • Since you are using jQuery, the event object is already normalized, there is no need to have browser specific code in it. so `$(".selectbox").on("click", function (e) { var parent = $(e.target).parent(); });` – Arun P Johny May 18 '15 at 11:23
  • 1
    @ArunPJohny—or far more efficient: `e.target.parentNode`. ;-) – RobG May 18 '15 at 11:27

2 Answers2

2

The element returned by jQuery is wrapped. Use find_parent(selectBoxEl[0]);

Varis
  • 254
  • 2
  • 11
  • You mean the Object returned by *.find* is not a DOM element, it's a jQuery instance and doesn't have a *parentElement* property (though I daresay there will be a *parentElement* method one day that returns another jQuery object with a single member that is the parentNode of the first element in the matched collection, or no members at all). – RobG May 18 '15 at 11:33
1

As already you are using jQuery, there is no need use separate function to identify parent DOM element. $('#id').parent() returns parent DOM element.

Still if you want to use .parentElement javascript method, use below method.

$('#id')[0].parentElement

JQuery is not actually returning any DOM element, it will return only instance of DOM object. parentElement propery has to be apply only for DOM element not for instance object.

Srini
  • 348
  • 1
  • 2
  • 17