Arrow
Arrow

Reputation: 2904

Get id of link when id is dynamically generated

I have a div with a bunch of stuff in it. I also have a link inside that div, which has a dynamically generated id. There's no way to tell what the id will be.

When I click that link, how can I get the id of that link into a variable jQuery? In a *.js file?

Upvotes: 0

Views: 140

Answers (3)

Kristian
Kristian

Reputation: 21810

Unless something gives the element an id, there won't be one.

But, for the sake of explanation, lets say there definitely is an ID on that link..

if you were using jQuery, you could simply select its container div and then traverse down to the link: var myID = $('div#theContainingDiv').children('a').attr('id');

or, you can just do what the other people said to do -- that will work too.

Upvotes: 0

Adil
Adil

Reputation: 148110

Try this,

With Tag Name

$('a').click(function(){
 //alert($(this).attr('id');  
 alert(this.id); //Better then the statement above as it is javascript with jQuery wrapper
});

With class

$('.classOfAnchor').click(function(){
 alert($(this).attr('id');
 alert(this.id);  //Better then the statement above as it is javascript with jQuery wrapper
});

Upvotes: 2

Lowkase
Lowkase

Reputation: 5699

$("a").click(function() {
    //alert( $(this).attr('id') );
     alert(this.id); //Better then above
});

Upvotes: 2

Related Questions