2

I try to add CSS class to <li> element, when I click on the button but addClass not working.

Here is my JS:

$('.test').click(function(event) {
    var centrum1 = $('.p17');
    $('section.bok-map').find( centrum1 ).addClass('active-region');
});

And this how is looking HTML code: enter image description here

Where is the problem? find() returns true.
Here is demo: http://demo.vrs-factory.pl/mapDemo/

8
  • .find() should return element wrapped with jQ Commented Apr 3, 2016 at 10:25
  • 1
    @Vertisan it works for me. Have you defined .active-region somewhere in the css? if i set it to .active-region{color:red} it works Commented Apr 3, 2016 at 10:27
  • Yes, when I add this class manualy in debbuger, so it's working but only this function won't add class Commented Apr 3, 2016 at 10:29
  • 1
    Can you share executable demo/snippet or JSFiddle ? Commented Apr 3, 2016 at 10:30
  • @RayonDabre Sure, here you are: demo.vrs-factory.pl/mapDemo Commented Apr 3, 2016 at 10:35

1 Answer 1

1

You had a couple of errors, as you were not selecting the correct element, hence the length of the selector was 0.

Firstly, the class is called pl7 not p17 and secondly, when using removeClass you don't put the . before the name of the class. As you are using removeClass it is understood that you want to target a class, hence not requiring you to specify this by adding the dot.

 <script>
      var centrum1 = $('.pl7');

      $('.test').click(function(event) {            
          $('section.bok-map').find( centrum1 ).removeClass('pl7');
      });

 </script>

Also, it may be worth noting that since you are only referencing$(.pl7) once you do not necessarily have to assign it to a variable. You could also write it as below. It is up to you.

  $('.test').click(function(event) {            
       $('section.bok-map').find('.pl7').removeClass('pl7');
  });
Sign up to request clarification or add additional context in comments.

2 Comments

@RayonDabre I was just fixing his code as he had it.
I get caching elements that are selected multiple times but is it more efficient to cache elements that are selected only once?

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.