There is a code:

<div id="block"> <span></span> </div> $('#block').click(function(){ $(this, 'span').addClass('content'); }); 

What am I doing wrong? Does not work. It is necessary to add a class for the span.

  • @ aa22, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina

2 answers 2

Clearly, I did not immediately understand what it was about and what was not working.

You incorrectly use a sample, according to the documentation $(выражение, контекст) , that is, this and 'span' should be swapped.

 $('#block').click(function(){ $('span', this).addClass('content'); }); 
  • one
    this code adds the content class to the div. And to the span-y as an option to do so jsfiddle.net/ftf6Ltww/2 - mountpoint
  • Yes, the code works. But he adds a class for the div, and it’s necessary for a span - aa22
  • mountpoint thanks, works - aa22
  • Another question arose: what about using .toggle () to make it click once - one class was added, the second - the second? For some reason, it adds display none. - aa22
  • one
    @ aa22, according to the documentation , the toggle () function is not intended for such actions. It shows or hides the item depending on the current state. If you need to add classes, you can use the hasClass check followed by addClass. If you click to add or remove one class, then toggleClass (). In general, see the documentation (office or Russian translation), there are examples in addition. - Alex Krass

Is it not so? Judging by the question, inside only span?

 $('#block').click(function(){ $(this).children().addClass('content'); }); 

And with the switch once or twice:

 $('#block').click(function(){ if( $(this).children().hasClass('first')) { $(this).children().addClass('second'); } else { $(this).children().addClass('first'); } });