ivannaxara ivannaxara - 2 months ago 8
Javascript Question

jQuery on click redirect to child href attribute

I´m trying to link one div with the href attribute of his first href my html looks like this

<div class="clicked">
<a class="i-want-this-href" href="target">
<img>
</a>
<a class="this-one-is-useless" href="Wrong-target">
<img>
</a>




And I have tested some different ways like this:

$('.clicked').on('click',function(){
aux= $('this:first-child').attr("href");
console.log(aux);
});


But I always get
Undefined
on the console. And I want to get "target" inside the first
<a>
element

Any help will be preciated!

Answer

Your selector is incorrect, you can use .find()/.children() along with :first selector

aux= $(this).find('a:first').attr("href");
Comments