Why at hover only one element is animated? although id is the same given. With hover CSS, every element with the same class / id is animated. How to achieve this on JS?

$('#img_one').hover(function(){ $('#img_one').addClass('animated infinite bounce'); }, function(){ $('#img_one').removeClass('animated infinite bounce'); }); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://placehold.it/350x150" alt="img" id="img_one" /> <img src="http://placehold.it/350x150" alt="img" id="img_one" /> 

  • The selection by id implies the uniqueness of an element with such an id . Accordingly, $('#img_one') contains a reference to only one DOM element - the first one found. - Igor
  • I see, thanks! I always use class in CSS, but now I checked <p id="img_one">TEST</p> <p id="img_one">TEST2</p> #img_one:hover{ color: red; } #img_one:hover{ color: red; } Works in CSS for both elements. Another such question: "Choice by id implies the uniqueness of an element with such an id" is this rule for all JavaScript or only in jQuery? - Alexander Kazakov
  • The question after all is not about the application of css classes, but about the selection of elements. I admit that in the case of #img_one:hover{ color: red; } #img_one:hover{ color: red; } action goes the other way - from the famous element to the style. - Igor

2 answers 2

First: you must use not id , but class . For these elements are many. When working with css you sort of should have known this.

Secondly: use this as a pointer to the element over which the event occurs.

 $('.img_one').hover(function(){ $(this).addClass('animated infinite bounce'); }, function(){ $(this).removeClass('animated infinite bounce'); }); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://placehold.it/350x150" alt="img" class="img_one" /> <img src="http://placehold.it/350x150" alt="img" class="img_one" /> 

  • Yes, just in CSS I always use the class . I'm just starting to learn JS / jQuery and read somewhere that it's better to use id to manipulate DOM. Your option solved my problem, thanks! - Alexander Kazakov

 $('.img_one').hover(function(){ $('.img_one').addClass('animated infinite bounce'); }, function(){ $('.img_one').removeClass('animated infinite bounce'); }); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://placehold.it/350x150" alt="img" class="img_one" /> <img src="http://placehold.it/350x150" alt="img" class="img_one" />