Skip to content Skip to sidebar Skip to footer

Jquery Can't Change Class Of All Spans Inside A Div

In the following example, how can I change the class of all the that are inside a particular h2
, while leaving the one that was clicked unchanged?

Solution 1:

change all spans class, and add $(this).removeClass("class_name");

Solution 2:

The easiest way would be:

$('div.h2 span').click(function() {
    $('div.h2 span').not($(this)).removeClass('like');
})

Solution 3:

$(".like").click(function() {
    $(this).parents(".h2").children("span").each(function(i, ele) {
        $(ele).removeClass("like").addClass("abc");
    });
    $(this).addClass("like")
});

Solution 4:

You can store the clicked element using a closure variable and find its siblings in the ajax callback.

$(function() {
    $(".like").click(function() {
        var $this = $(this);

        var hasLike = $this.data("id");
        vardata = 'id='+hasLike;
        console.log($this.data('id'));

        if(hasLike) {
            // ajax call
            $.ajax({
                type:"GET",
                url:"demo.php",
                data:data,
                beforeSend:function(html){
                    // We'll think of something to do here
                },
                success: function(page_data){
                    // Remove class like, add class no-like
                    $this.closest('.h2').find('.like').not($this).removeClass('like').addClass('no-like');

                },
                error: function(yikes){
                    //To do later
                },
            });
        }
        returnfalse;
    });
});

Solution 5:

Answer written in your present code context. There are other options like other answered.

$(".like").click(function() {
    //first option
    $(this).parent().siblings().children().css('background-color', 'red');
    //second option
    $(this).closest('.h2').find('span').not(this).css('color', 'yellow'); 
});

There are two different options to access <span>. I don't know which option will perform better.

Here, replace .css() method with .addClass(), removeClass() or toggleClass()

jsFiddle

Post a Comment for "Jquery Can't Change Class Of All Spans Inside A Div"