-1

I have two elements with class "rate". The first element has id="1", and the second has id="2". When i use my selector :

    $(".rate").click(function()
    {
      var id=$(this).attr('id');
      alert(id);
      //Do something here
    }

I get answer = 1. How can i get the element with class="rate" and id = "2" ?

  • 4
    By clicking on the item with id = 2? Sorry, it's not clear why the code is in click handler. – raina77ow May 21 '15 at 15:26
  • 2
    Works fine here: http://codepen.io/paulroub/pen/Mwjvxa. Can you show the some HTML that demonstrates the problem? – Paul Roub May 21 '15 at 15:27

1 Answers1

0

If you want the element, you can use this, as you already have

$(".rate").click(function()
{
  var element = $(this);
  //Do something here
});

If you want the ID, you seem to have forgotten to close off your code with a );

For me it works as such: https://jsfiddle.net/jc1a402a/


Also, you shouldn't have ID's that start with a number:

See this question: can i have a div with id as number?

Community
  • 1
  • 1
Davy
  • 691
  • 1
  • 7
  • 18
  • "See this question: can i have a div with id as number?" ... and its first, top-rated answer, beginning "yes, you can". :-) A very-widely-supported misbehavior in older browsers, now validated by HTML5. Still looks weird to me, but not particularly dangerous. – Paul Roub May 21 '15 at 15:36
  • It says 'Yes you can', but explains below that CSS selectors will give you a lot of trouble: "If you're going to use those ids [...] be aware that it can be a pain, because you can't use an id starting with a digit in a CSS id selector literally; you have to escape it." – Davy May 21 '15 at 15:39
  • 1
    Well, yes, except for that *completely valid and important* reason. I'd delete my comment if it wouldn't render yours nonsensical. – Paul Roub May 21 '15 at 15:43