Home > Software design >  How do i get the individual a tag href #id when click
How do i get the individual a tag href #id when click

Time:09-23

What im getting is only the first #, what i want is when i click ill get the individual # eg:#intro2_tab

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    var test1 = $(".sub_navi li a").attr('href');

    if (window.location.hash.indexOf(test1) ) {
        console.log("your url contains the name"   test1);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


    <ul class="sub_navi">
        <li id ="sub_intro" class="active"><a href="#intro_tab">Intro </a></li>
        <li id="sub_intro2"><a href="#intro2_tab">Intro 2</a></li>
        <li id="sub_intro3"><a href="#intro3_tab">Intro 3</a></li>
        <li id="sub_intro4"><a href="#intro4_tab">Intro 4</a></li>
    </ul>

CodePudding user response:

You need to us $(this) to catch the href of the clicked item

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    var test1 = $(this).attr('href');

    if (window.location.hash.indexOf(test1) ) {
        console.log("your url contains the name"   test1);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


    <ul class="sub_navi">
        <li id ="sub_intro" class="active"><a href="#intro_tab">Intro </a></li>
        <li id="sub_intro2"><a href="#intro2_tab">Intro 2</a></li>
        <li id="sub_intro3"><a href="#intro3_tab">Intro 3</a></li>
        <li id="sub_intro4"><a href="#intro4_tab">Intro 4</a></li>
    </ul>

I kindly ask you to rate my answer

  • Related