Sam
Sam

Reputation: 6354

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>

Upvotes: 2

Views: 1780

Answers (4)

RAJNIK PATEL
RAJNIK PATEL

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

Mayank Pandeyz
Mayank Pandeyz

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

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

PrashanthBR
PrashanthBR

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

Related Questions