Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of an anchor tag in jQuery?

Tags:

jquery

How to get the id of an anchor tag in jQuery? This is the tag.

 <ul class="formfield">
     <li class="selected"><a href="" id="text">Text</a></li>
     <li><a href="" id="textarea">Textarea</a></li>
 </ul>

I need to get the id, i.e., textarea,text etc in a variable.

I tried something like this,but there is no such thing as fieldValue I suppose.

$('.formfield a').click(function() {         
    fieldType=$('.formfield a').fieldValue();
    alert(fieldType);
});
like image 774
Angeline Avatar asked Jun 26 '09 06:06

Angeline


2 Answers

To get the id attribute of a field, you would do:

$('ul.formfield a').click(function() {
    var id = $(this).attr('id');
    alert(id);
});

To get the text contents of the a tags (the text between the opening and closing tags), you would do:

$('ul.formfield a').click(function() {
    var text = $(this).text();
    alert(text);
});

Please note the usage of $(this) inside the click function. You were re-using the selector which would not do what you want. Inside the event handler, this refers to the element being acted on, so with the code above you would get 'text' or 'textarea' depending on which one you clicked.

like image 72
Paolo Bergantino Avatar answered Nov 09 '22 04:11

Paolo Bergantino


You said you want it in a variable?

Here you go:

var myvariable = $('ul.formfield a').attr('id');

It will give you the id of the first matched element, or in your example "text".

like image 40
Evgeny Avatar answered Nov 09 '22 02:11

Evgeny