0
votes

I have to select multiple elements, all them have the class ="org-box". Inside that box there is a link a that I want to capture the href. So I do this

$("a.org-box").click(function (e) {
 e.preventDefault();
 var link = $(e).html();
 $('.col-right').prepend("<b>" + link +"</b>");
})

What I always get is null, and I have tried other selectors like
var link = $(e.a).attr("href").html();

With the same luck.

I checked what I get from that selection $("a.org-box") and I get this -> b.fn.b.init[102]

If I do this $("a.org-box:first").attr("href"); I get correctly the href, but when I do $("a.org-box").attr("href"); I just get the first one.

What Im doing bad ?? How to select all the a.org-box and capture href on click ?

3
/facepalm Do people not read documentation anymore? api.jquery.com/click Says you get the eventObject as a parameterTheZ
Which browser are you using? the jQuery factory function (jQuery or $) returns jQuery.fn.init, but because they're sourced from minified code the name will show up as b.fn.b.init.zzzzBov
dam $(this) solved it.... thx alot and sorry for be so noobNonyck

3 Answers

2
votes
<a href="http://google.com" class="org-box">Click to prepend Google</a>

--

$("a.org-box").on('click', function(e) {
    e.preventDefault();
    $('.col-right').prepend("<b>" + e.target.href +"</b>"); //http://google.com
});

FIDDLE

0
votes

You could use:

$("a.org-box").click(function (e) {
    $('.col-right').prepend('<b>' + $(this).attr('href') + '<b>');
    e.preventDefault();
});

this is set to e.target, with e.target being the target of the event (the item that was clicked on). You can use $(this).attr('href'), $(this).prop('href'), this.href, or any of the same variants using e.target.

I can't tell is whether you need the inner text (.text()) of the link, or the href attribute, so I'm assuming the latter.

0
votes

jQuery selectors return ALL matched elements, so what's happening is you're getting the jQuery collection of those elements back from the selector, the event data is NOT the element that triggered the event a correct implementation would be:

$(a.org-box).click(function(){
    var link = $(this).html();
    $('.col-right').prepend("<b>" + link +"</b>");
});

you use $(this) because jQuery is iterating over the collection so just like if you were using .each() the this object holds your element.