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

3
  • possible duplicate of How to get all CSS classes of an element? Commented Feb 29, 2012 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. Commented Feb 29, 2012 at 16:02
  • None of your divs have an id? Do you mean how to you get the number out of the class name? Commented Feb 29, 2012 at 16:03

3 Answers 3

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-', '');
});
Sign up to request clarification or add additional context in comments.

Comments

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
});

3 Comments

You are not using on correctly, it is as good as bind('click',...). This is not going to work for dynamically created elements.
I've edited it, though I don't think this is relevant for this question.
And now I read again the question, I realized the "that are generated dynamically" part, so thanks :)
0

The correct jQuery syntax is:

$("div").click( function() { 
    var id = $(this).attr('class').replace('div-', '');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.