2

I have many divs in a page, like so:

<div class="formitem food-6 group-7">
//content of div
  <input type="checkbox"> //child of div
</div>

<div class="formitem food-7 group-7">
//content of div
  <input type="checkbox"> //child of div
</div>

When a checkbox is checked, I want to store the value of it's parent's unique class e.g "food-6" or "food-7" in a variable. I can get all the classes of the parent, like this:

parent = $(this).closest(".formitem").attr("class");

Which gives me formitem food-7 group-7.

How can I get "the one that starts with food-" ?

1
  • 4
    Since it looks like you're using this food-7 class for computation instead of CSS, have you considered using data- attributes instead? Commented Oct 28, 2013 at 16:14

3 Answers 3

6

Try a simple regex like

parent = $(this).closest(".formitem").attr("class").match(/\b(food-\d+)\b/)[1];
Sign up to request clarification or add additional context in comments.

1 Comment

in this case both are same... just went with the grouped item
2

Use a regular expression

...attr("class").match(/food-\d+/)

if you want just the number

.match(/food-(\d+)/)[0]

Comments

0
$(':checkbox').click(function(){
    var parent_class = '';
    parent_class = $(this).parent('div').attr('class').match(/food-\d+/);
    alert(parent_class);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.