Search code examples
jqueryhref

Get href attribute from sibling's child jQuery?


I'm using the following code to try and get the href data from a another element, it keeps returning "undefined" what am I doing wrong?

$('.linkbutton').bind('click', function(e) {
        e.preventDefault();
        var flagURL = $(this).siblings().next('.flag-action').attr('href');
        console.log(flagURL);
    });
<div class="linkbutton">
<h4 class="quoteflag">
    <a href="/demo/url/here" title=" " class="flag-action">
    </a>
</h4>

Solution

  • instead of

    var flagURL = $(this).siblings().next('.flag-action').attr('href');
    

    try the below code:

    var flagURL = $(this).siblings().find('.flag-action').attr('href');
    

    Because next() selector will return you the next sibling. But you need the child of next sibling. Find() selector will give you all the descendants of a particular element. In your case, you can as well use children() selector instead of find() since you are trying to find immediate child of H4 element.