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?
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.
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.
click(function() { var id = $(this). attr('id'); $container. cycle(id. replace('#', '')); return false; });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With