Gannicus
Gannicus

Reputation: 530

Why can't I add class to this html element?

I'm trying to add this the active class to the element when the user clicks it. Why does it not work? Is there something wrong with the syntax?

HTML code:

  <div class="accordion">
            <h3>a</h3>
            <p class="active">b</p>

            <h3>a</h3>
            <p>b</p>

            <h3>b</h3>
            <p>b</p>

            <h3>b</h3>
            <p>b</p>
        </div>

jQuery code:

jQuery(function($) {

    $('div.accordion').click(function(e) {
        e.preventDefault();
        $(this).addClass("active");
    });
});

What i wanna do is when the user clicks h3, thats when it sets the p tag below it the active class

Upvotes: 0

Views: 1165

Answers (3)

dfsq
dfsq

Reputation: 193261

You need to bind click event to H3 elements. Also make sure you remove previously active elements:

var $h3 = $('.accordion > h3').click(function(e) {
    e.preventDefault();
    $h3.next('p').removeClass('active');
    $(this).next('p').addClass('active');
});

Demo: http://jsfiddle.net/2DB37/

Upvotes: 2

shyammakwana.me
shyammakwana.me

Reputation: 5752

WORKING DEMO

change jQuery to like this

jQuery(function($) {

    $('div.accordion p').click(function(e) {
        e.preventDefault();
        $(this).addClass("active");
    });
});

UPDATED DEMO

jQuery(function($) {

    $('div.accordion h3').click(function(e) {
        e.preventDefault();
        $(this).next().addClass("active");
    });
});

Upvotes: 0

filype
filype

Reputation: 8380

I'm trying to add the active class to the p tag.

You forgot to add a click event to the p tag:

jQuery(function($) {

    $('div.accordion h3').click(function(e) {
        e.preventDefault();
        $(this).next('p').addClass("active");
    });

});

Upvotes: 1

Related Questions