Jerome
Jerome

Reputation: 1192

How to change the CSS of an HTML element with JavaScript

After reading some questions/answers about this subject I have tried to make it works for me but I can't.

The story line is that I have X elements (so it means no ID just class) and I want to change the background when I click in one.

So with JS I did:

'click .switch' (event) {
    event.toElement.closest("li").css('background-color','black');


    if(this.stateMachine == 'running'){
      Meteor.call("switch", this.nameMachine);
    }

  },

to get the container (here a <li class="liMachine switch">) but I have this error:

event.toElement.closest(...).css is not a function

Despite the event.toElement.closest returns the right element: enter image description here

So what am I doing wrong ?

Upvotes: 0

Views: 113

Answers (2)

Cristina Jadi Martins
Cristina Jadi Martins

Reputation: 26

Since you are using Meteor, you may prefer this syntax:

"click .switch": function(event){
$(event.target).css("background-color", "black");
}

Upvotes: 0

caramba
caramba

Reputation: 22490

$('.liContainer.switch').on('click', function() {
    $(this).toggleClass('active');
});
.active {
  background-color: powderblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liContainer switch">one</li>
  <li class="liContainer switch">two</li>
  <li class="liContainer switch">three</li>
</ul>

If $(event.target) works for you then the problem was of course that you did not pass a jQuery object. So you can not use jQuery functions on non jQuery object.

Upvotes: 4

Related Questions