Teli
Teli

Reputation: 57

Alert ID of element when clicked

I'm trying to figure out how to display this span's ID in an alert when the span is clicked. More specifically, I need it to display "Movie" so that I can select spans by "Movie" later on.

How can this be achieved? Thank you.

http://jsfiddle.net/neowot/x4yfracg/2/

HTML

<div id="Movie" class="Fun">

    <div class="lister">
        <ul class="active"><span>Rodeo</span></ul>
    </div>

</div>

CSS

.lister ul span {
    cursor:pointer;
}

JS

$(document).ready(function() {

    $(document).on('click', '.lister ul span', function(event) {  
            alert( $(this).attr('id') );
    }); 

}); 

Upvotes: 0

Views: 919

Answers (3)

Renan Ara&#250;jo
Renan Ara&#250;jo

Reputation: 3631

Use closest searching for ".Fun" on ancestors in the DOM tree:

$(document).on('click', '.lister ul span', function(event) {  
        alert( $(this).closest(".Fun").attr('id') );
}); 

http://jsfiddle.net/x4yfracg/5/

More information about closest() function: https://api.jquery.com/closest/

Upvotes: 3

guradio
guradio

Reputation: 15555

$(document).ready(function () {

    $(document).on('click', '.lister', function (event) {
        alert($(this).find('span').attr('id'));
        alert($(this).parent().attr('id'));
    });

});

FIDDLE

First put an attr id to span. What you can do is put the click event to class lister then get the id of the span found inside of that class.Then use .parent() to get its parent and you can now get the parents id as well

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

$(document).on('click', '.lister ul span', function(event) {  
    console.log( $(this).closest("div").parent().attr("id"));
}); 

Upvotes: 1

Related Questions