Jquery-store id of clicked link in variable

This should be basic, but for some reason it doesn't work for me. I just want to save the identifier when a link that has a specific class is clicked in a variable, for example:

<a href="#" id="this_id_here" class="only_this_class">Some link</a> 

I would like jquery to get the link id above and store it in a variable. I tried $ this.attr ("id") and $ this.id but did not work.

This is what I have for jquery:

  $(".only_this_class").click(function() { var clickedId= $(this).attr("id"); alert(clickedId); }); 

I just get "undefined" every time.

+4
source share
3 answers

I removed the space between this and _class in class="only_this _class" and it works for me.

Try here

Please see jQuery Selectors

If you have two classes in your HTML, then the syntax is different:

 $('.classA.classB') 

See How to select an item with multiple classes?

+3
source

NAVEED is right if you remove the space in which it works, because if there is a space, HTML will put two classes in the class: only_this and _class.

If you are really looking for two different classes, you must replace the space with a dot so that it works correctly, as in $(".only_this._class")

+2
source

$(".only_this _class") this selector will look for the _class tag in the .only_this element. Perhaps you are looking for $(".only_this") that will select the element that this class has. Try it.

  $(".only_this").click(function() { var clickedId= $(this).attr("id"); alert(clickedId); }); 
0
source

Source: https://habr.com/ru/post/1369337/


All Articles