-1

I have this:

<ul class="tabs">
    <li><a href="#home">Home</a></li>
    <li><a href="#credits">Credits</a></li>
    <li><a href="#about">About</a></li>
</ul>

and I want to get the clicked item list href value with an event listener on the ul tag, something like this:

    $('.tabs').click(function () {
        let getClickedItem = 
    })
2
  • Can you specify what exactly what you want to see? Is it link value, or text, or HTML itself? Commented Apr 4, 2020 at 23:10
  • I want to get the link value
    – Wxcc
    Commented Apr 4, 2020 at 23:13

2 Answers 2

0

Put this code and out console, this should be thing you are looking for:

$(function(){
            $(".tabs li a").click(function(e){
                e.preventDefault();
                console.log($(this).attr('href'));
            })
        })
3
  • Why do I have to put preventDefault()? It seems working without.
    – Wxcc
    Commented Apr 4, 2020 at 23:27
  • Ok, sorry I haven't seen the end of your response, and in which case the event does not get explicitly handled?
    – Wxcc
    Commented Apr 4, 2020 at 23:51
  • @Hunam you need to put preventDefault() to stop going to the links you have in the "href" attribute. for example you can put any website to check instead of #home or #credits, it will automatically it will go there untill you put back preventDefault() Commented Apr 5, 2020 at 9:45
0

You can access the target property on the event object:

$('.tabs').click((event) => {
  console.log(event.target);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="tabs">
    <li><a href="#home">Home</a></li>
    <li><a href="#credits">Credits</a></li>
    <li><a href="#about">About</a></li>
</ul>

This will however give the element that was clicked which in this case would most definitelly be the anchor tags.

You say you want the list item that is clicked. You could just attach the event listener directly to those:

$('.tabs li').click(function () {
  console.log('click', this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="tabs">
    <li><a href="#home">Home</a></li>
    <li><a href="#credits">Credits</a></li>
    <li><a href="#about">About</a></li>
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.