jack blank
jack blank

Reputation: 5195

How to get the whole (parent) element not just the specific child after using e.target

In the code below I want to target the li to see if that li was clicked. Currently, when I click on the text of the li the e.target is the span, which is the child of the li, so it is like I'm not clicking on the li (I guess e.target is very specific). The li is in a drop down menu so i am using e.target to get which option the user wants. If the user picks li with a class 1 set global variable. If the user picks li with a class of 2 set a diff global variable. What,s the best way to target the whole li?

 $(document).ready( function(){
        var clicked = ["subtraction"]
        $(".add-section").on("click", function(e){
            console.log(e.target)
            clicked = []
            clicked[0] = "addition"
            $("#gameArea").html(clicked[0])
            if(!$(".add-section ul").is(":visible")){
                $(".add-section ul").css("display" , "block")
            }else{
                $(".add-section ul").slideUp("fast")
            }
            if($(e.target).hasClass("one")){
                alert("one")
            }
        })
    });

html:

<div class="add-section">
    <span>add</span>
    <ul>
        <li class="one"><span class = "left" id = "add2">Add 2 items</span> <span class= "right">2d</span></li>
        <li class= "two"><span class = "left" id="add3">Add 3 items</span> <span class= "right">2d</span></li>
    </ul>
</div>

Upvotes: 1

Views: 70

Answers (2)

PeterKA
PeterKA

Reputation: 24638

In place of:

$(e.target).hasClass("one")

use:

$(e.target).closest('li').is('.one')

.is() | jQuery API Documentation
.closest() | jQuery API Documentation

Upvotes: 1

Alex
Alex

Reputation: 51

You're looking for e.target.parentNode

Upvotes: 1

Related Questions