Cool Shape Cool Shape - 1 month ago 12
Javascript Question

Jquery get closest a href attribute

I have the below markup and I am trying to get the href but always getting undefined. Any help is appreciated.

<div class="wrapper">
<span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)">
<a href="http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg"></a>
</span>
<div class="mixDivRight">
<p class="bottomP"><button>Select</button><p>
</div>
</div>

$container = $('.wrapper');
$container.on('click', '.bottomP', function (event) {
console.log($(this).closest('a').attr('href'));
});

Answer

Assuming that you fix the class/ID issue noted in the comments by Mohammad you could use:

$('.wrapper').on('click', '.bottomP', function (event) {
    console.log($(this).closest('.wrapper').find('a').attr('href'));
});

$('.wrapper').on('click', '.bottomP', function (event) {
    console.log($(this).closest('.wrapper').find('a').attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <span class="mixSpanLeft" style="background-image: url(http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg)">
        <a href="http://cdn.wallpapersafari.com/29/20/3HE5Mx.jpg"></a>
    </span>
    <div class="mixDivRight">
        <p class="bottomP"><button>Select</button><p>
    </div>
</div>

Comments