0
<div class="group group2">
  <div class="groupHeader">New Group</div>
    <ul>
      <li><span class="moreLinks">Add a link</span></li>
    </ul>
  </div>
</div> 

How can I get the class "group2" when the user clicks the class "groupHeader"? I tried it with prev()but it returned undefined.

1
  • .parent() is what you need Commented Jun 15, 2015 at 10:47

5 Answers 5

6

Use .parent() or .closest() instead of .prev() like this:

$(".groupHeader").closest("div").attr("class");
$(".groupHeader").parent("div").attr("class");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks all of you guys! parent() worked for me. Silly me :D
@ColdStormy Glad, that it helped you! Enjoy!
6

You need to use .parent() instead of .prev() as the div element with class group2 is immediate parent and not previous sibling.

$(".groupHeader").click(function(){
 var classnames = $(this).parent().attr("class")
});

Comments

5

use parent()

$(".groupHeader").click(function(){
   $(this).parent().attr("class");
});

Comments

1

Use the jquery parent() function instead:

$( ".groupHeader" ).click(function() {
 $(this).parent().css( "background", "yellow" ); 
});

I made a fiddle for you here ;-) https://jsfiddle.net/qLkt5z83/

Comments

0

You specifically asked for "group2" so here you go:

$(".groupHeader").click(function()
{
    var groupNo = $(this).parent().attr("class").replace('group ', '');

    alert(groupNo);
});

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.