Reputation: 6354
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>
Upvotes: 2
Views: 1780
Reputation: 1049
$('.linkbutton').bind('click', function(e) {
e.preventDefault();
var flagURL = $(this).siblings().find('.flag-action').attr('href');
console.log(flagURL);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linkbutton">linkbutton div</div>
<h4 class="quoteflag">
<a href="/demo/url/here" title=" " class="flag-action">
</a>
</h4>
Upvotes: 0
Reputation: 26258
You can get href
by using find('.flag-action')
as a
is a children of .linkbutton
like:
$('.linkbutton').bind('click', function(e) {
e.preventDefault();
var flagURL = $(this).find('.flag-action').attr('href');
alert(flagURL);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linkbutton">Click here
<h4 class="quoteflagdiv">
<a href="/demo/url/here" title=" " class="flag-action">
</a>
</h4>
Upvotes: 1
Reputation: 27041
You will have to use .find()
and not .next()
because that flag-action
is a child and not an element next to your quoteflag
$('.linkbutton').bind('click', function(e) {
e.preventDefault();
var flagURL = $(this).siblings().find(".flag-action").attr("href");
console.log(flagURL);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linkbutton">click</div>
<h4 class="quoteflag">
<a href="/demo/url/here" title=" " class="flag-action">
</a>
</h4>
Upvotes: 3
Reputation: 183
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.
Upvotes: 0