tags:

views:

881

answers:

2

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);
});
+5  A: 

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.

Paolo Bergantino
"this.id" would also have the value (it's standard for a DOM element)
Thomas G. Mayfield
Thank you......
Angeline Aarthi
A: 

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".

Evgeny