Question

I'm new in jQuery and my question is probably obvious for most of you.

I want to add a class to a specific class

in short, my page has the following tags:

<div class="content">
   blabla   1111
    <a href="#" id="1">Test link</a>
</div>
<div class="content">
   blabla  2222
    <a href="#" id="1">Test link</a>
</div>

when I click on one of the link I want to add a class just below it.

so if click on the first link, I want to add a class comment

the jQuery command $(content).addclass("comment") of course create the comment class below the both div class content, I want only to add below the clicked link.

Was it helpful?

Solution

You can use $(this) to target current clicked element:

$('.content').click(function() {
    $(this).addClass('comment');
});

Also id is unique, you should use class for your anchors instead.

If you want to add class comment on .content div when click on the anchor than you can use:

$('.content a').on('click',function(e){
    e.preventDefault();
    $(this).closest('.content').addClass('comment');
})

OTHER TIPS

When the link is clicked select the next element after the parent element.

$("a").click(function(){
    $(this).parent(".content").next(".content").addClass('comment');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top