1

i am new with jquery. i am trying to find the "href" attribute of targeted element.

I have written a script for click event for each class "link-redirect".In this trying to select href for target element using data-target attribute.

But by using my script i am always getting href of first div i.e "link1".

what wrong i am doing here ?

<div class="link-redirect" data-target=".title-link">
    <div cass="div1">
        <a href="link1" class="title-link">LInk</a>
    </div>
</div>
<div class="link-redirect" data-target=".title-link">
    <div cass="div1">
        <a href="link2" class="title-link">LInk</a>
    </div>
</div>
<div class="link-redirect" data-target=".title-link">
    <div cass="div1">
        <a href="link3" class="title-link">LInk</a>
    </div>
</div>
<div class="link-redirect" data-target=".title-link">
    <div cass="div1">
        <a href="link4" class="title-link">LInk</a>
    </div>
</div>

<script>
    $('.link-redirect').each(function(){
        $(this).on( "click", function() {
            var self = $(this);
            var link = $(self.data('target')).attr('href');           
            alert(link);           
        });
    });
</script>
2
  • The class is on the div, not the a. Commented Jan 20, 2014 at 6:14
  • Why data-target element? Commented Jan 20, 2014 at 6:26

4 Answers 4

2

You need to find the anchor element relative(descendant in this case) to the current link-redirect element

$('.link-redirect').on("click", function () {
    var self = $(this);
    var link = self.find(self.data('target')).attr('href');
    alert(link);
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

Missed that data. You got it.
@Anup: getting undefined .
@Kango in that case the html provided by you might be different from what you have in your page... did you check the attached demo
I got my issue.my html structure slightly different.
1

Try to use the context feature provided with Jquery selectors,

 $('.link-redirect').click(function(){
      var link = $($(this).data('target') , $(this)).attr('href');           
      alert(link);           
 });

DEMO

2 Comments

@sarath Sure :) But OP is not asking about that i guess.
@Kango Did you test the demo provided by me.?
1

You should your anchor tag in your div element and don't use each() or loops to bind click event try this,

$('.link-redirect').on("click", function (e) {
    var self = $(this);
    var link = self.find('a').attr('href');
    alert(link);
});

Demo

Comments

0

This would be the simplest way:

$('.title-link').on("click", function () {
   alert($(this).attr("href"));

});

jsfiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.