user8682821
user8682821

Reputation:

Removing element class onclick using JS (not working)?

I've had a look around but I've not found anything that can really address the issue that I'm having and although I can read and write basic JS I'm still finding it tricky to debug my own problems.

I'm trying to remove a class from an element onclick and for some reason .removeClass isn't working as expected. I'm already using some JS to trigger style changes (also onclick) so I know the element ID and classes are correct.

Trigger Element: #gsbtns1 .vc_btn3-color-grey

Class to remove: .nest-custom-activator


Here is part of my working 'style' JS:

<script>
jQuery('#gsbtns1 .vc_btn3-color-grey').click(function() {
    jQuery('#gsbtns1 .vc_btn3-color-grey').css({
        'opacity': '0.3',
        'cursor': 'auto',
        'pointer-events': 'none'
    });
});
</script>

Here is a screenshot and text copy of the trigger element in Console:

Console Screenshot:

enter image description here

Console Text:

<div class="vc_btn3-container  nest-custom-activator
 wpb_animate_when_almost_visible wpb_fadeIn fadeIn vc_btn3-inline 
 vc_custom_1505915503693 wpb_start_animation animated" id="gsbtns1">


I've tried this JS:

<script>
jQuery('#gsbtns1 .vc_btn3-color-grey').click(function() {
    jQuery(".vc_btn3-color-grey").removeClass("nest-custom-activator");
});
</script>

and this JS:

<script>
jQuery('#gsbtns1 .vc_btn3-color-grey').click(function() {
    jQuery("#gsbtns1 .vc_btn3-color-grey").removeClass("nest-custom-activator");
});
</script>


Sadly, neither of these are removing the .nest-custom-activator class.

Can anyone help me understand why this isn't working?

Upvotes: 3

Views: 689

Answers (3)

Stefdelec
Stefdelec

Reputation: 2811

You need to wrap it in $(document).ready(function(){})

<script>
 $(document).ready(function(){
$('#gsbtns1 .vc_btn3-color-grey').click(function() {
    $("#gsbtns1 .vc_btn3-color-grey").removeClass("nest-custom-activator");
});

})
</script>

And also I guess you element has the id gsbtns1 and the class vc_btn3-color-grey

  $('#gsbtns1.vc_btn3-color-grey')

No space between the Id and the class

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

Your screenshot shows it's parent and not the current element. Hence, you need:

jQuery('#gsbtns1 .vc_btn3-color-grey').click(function() {
    jQuery(this).parent().removeClass("nest-custom-activator");
});

Upvotes: 3

sree3505577
sree3505577

Reputation: 9

Replace your jquery code with the below one

html:

$('#gsbtns1.vc_btn3-color-grey').on('click',function() {
    $('#gsbtns1.vc_btn3-color-grey').css({
        'opacity': '0.3',
        'cursor': 'auto',
        'pointer-events': 'none'
    });
});
<div id="gsbtns1" class="vc_btn3-container  vc_btn3-color-grey nest-custom-activator  wpb_animate_when_almost_visible wpb_fadeIn fadeIn vc_btn3-inline vc_custom_1505915503693 wpb_start_animation animated" >
test</div>

jsfiddle

Upvotes: 0

Related Questions