0

I have some divs that are generated dynamically with content. I add the content id to the class for the div like so:

<div class="div-1"></div>
<div class="div-3"></div>
<div class="div-6"></div>
<div class="div-8"></div>

How do I select the id for a div because I need it as a param to send via ajax. e.g. I need to get the 1 when I click on the 1st div, 3 when I click on 2nd and so on

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mythriel
  • 1,360
  • 5
  • 24
  • 45
  • possible duplicate of [How to get all CSS classes of an element?](http://stackoverflow.com/questions/9279368/how-to-get-all-css-classes-of-an-element) – Felix Kling Feb 29 '12 at 16:01
  • I think you're confusing IDs with classes. If you switch the class="" to id="", then we're talking about IDs. You could bind $('div').click(function() {var this_ID = $(this).attr('id); this_ID.replace('div-', ''); }); Quick, dirty and untested. – isotrope Feb 29 '12 at 16:02
  • None of your divs have an id? Do you mean how to you get the number out of the class name? – jfriend00 Feb 29 '12 at 16:03

3 Answers3

1
var id = $(this).attr('class').replace('div-', '');

Or even simple

var id = this.className.replace('div-', '');

Where this points to the dom element you click on inside the click handler.

//Here instead of document it is better to specify a parent container of all divs
$(document).on('click', '[class^="div-"]', function(){
       var id = this.className.replace('div-', '');
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

Try this, and remember changing "div" for your selector:

$(document).on("click", "div", function() {
    var class_elem = $(this).attr("class").split("-");
    var n = class_elem[1];  // This is your number
});
mariogl
  • 1,195
  • 1
  • 10
  • 24
0

The correct jQuery syntax is:

$("div").click( function() { 
    var id = $(this).attr('class').replace('div-', '');
});
NickGreen
  • 1,742
  • 16
  • 36