Angeline
Angeline

Reputation: 2379

How to get the id of an anchor tag in 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);
});

Upvotes: 11

Views: 69850

Answers (3)

abdullah-sust
abdullah-sust

Reputation: 51

Below code snippet works for me.

<a id="56" class="slot">[01:40:00-01:45:00] </a>
$(".slot").click(function () {
    var id = $(this).attr('id');
    console.log(id);
});

Upvotes: 0

Evgeny Zislis
Evgeny Zislis

Reputation: 6957

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

Upvotes: 2

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

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.

Upvotes: 36

Related Questions