Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: get id from class selector

Is there any way that I can get the id of an element from something like:

<a href="#" class="test" id="test_1">Some text</a> <a href="#" class="test" id="test_2">Some text</a> <a href="#" class="test" id="test_3">Some text</a> 

and then I bind

$('.test')

so when I click one of the elements I get back the id?

like image 455
Oliver M Grech Avatar asked Mar 29 '11 09:03

Oliver M Grech


People also ask

How do I select an item using class and id?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I know which ID is clicked in jQuery?

click(function() { var id = $(this). attr('id'); $container. cycle(id. replace('#', '')); return false; });

What is the difference between id and class selector in jQuery?

Differentiate the concepts of ID selector and class selector: The only difference between them is that “id” is unique in a page and it is applied to one HTML element while “class” selector can apply to multiple HTML elements.


1 Answers

Doh.. If I get you right, it should be as simple as:

$('.test').click(function() {    console.log(this.id);  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <a href="#" class="test" id="test_1">Some text</a>  <a href="#" class="test" id="test_2">Some text</a>  <a href="#" class="test" id="test_3">Some text</a>

You can just access the id property over the underlaying dom node, within the event handler.

like image 185
jAndy Avatar answered Sep 30 '22 02:09

jAndy