Sergi Mínguez
Sergi Mínguez

Reputation: 69

jquery get parent id not children

I have this html code :

<div id="main-link-1" class="menu-option">
  <div id="icon" class="menu-icon"></div>
  <div class="menu-text"> Overview </div>
  <div class="separator"></div>
</div>

I just want to add jquery click event to parent .menu-option and get the id "#main-link-1" :

$('.menu-option').click($.proxy(this.navigatorLink,this));

And the navigatorLink function :

navigatorLink : function(event){
    if(event.preventDefault) 
        event.preventDefault();
    else 
        event.returnValue = false;


    var link = event.target;

    var linkId = $(link).attr('id');
}

The linkId should be always the parent id : "main-link-1"

But when I click over the children, I get the children id. How can I get only the parent_id event when I click hover the children?

I know it should be easy, but I don't find the way without changing the html, Thanks in advance!

Upvotes: 0

Views: 255

Answers (1)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

Thanks for posting the actual code in your question. That makes it a lot easier to answer.

The immediate issue is that by using proxy, you lose track of the default this parameter, and that's what you need to use to see the element that's getting the call. In using event.target, you get the exact element that is clicked on, not the element that catches the event propagation. (See http://javascript.info/tutorial/bubbling-and-capturing#this-and-event-target for a nice visual example of the difference between this and event.target.)

I guess the question is: why are you using proxy? It seems unnecessary, since you don't ever use this inside the function. Unless there's more to your code than that, I would do the following:

$('.menu-option').click(this.navigatorLink);


navigatorLink : function(event){
    if(event.preventDefault) 
        event.preventDefault();
    else 
        event.returnValue = false;

    var linkId = $(this).attr('id');
}

If you do have code that uses this, so you can't make the change that way, you can keep your old code and make use of closest:

navigatorLink : function(event){
    if(event.preventDefault) 
        event.preventDefault();
    else 
        event.returnValue = false;

    var link = event.target;

    var linkId = $(link).closest(".menu-option").attr('id');
}

Upvotes: 2

Related Questions