There is an html code:

<div class="fruits"> <p>1</p> <div> <div class="fruits"> <p>2</p> <div> <div class="fruits"> <p>3</p> <div> 

And there is a css code:

 .myfruits { margin: 20px; } 

How to change the value of the margin property of the .myfruits class only for 2 diva using js?

  • And why not through CSS? - Yuri

3 answers 3

Strange, in HTML fruits , and in CSS myfruits You myfruits get to the second element of the class myfruits something like this

 var e2 = document.getElementsByClassName("myfruits")[1]; 

To property margin

 e2.style.margin 

    JS answers the last answer. I offer a CSS solution:

     .fruits:nth-child(2) { margin: 20px; } 
     <div class="fruits"> <p>1</p> </div> <div class="fruits"> <p>2</p> </div> <div class="fruits"> <p>3</p> </div> 

      jquery - $("div:nth-of-type(2)").css("margin", "20px")

      • What about .eq(1) ? - Yuri
      • @Yuri I wrote so because the 2nd is hidden and the 2nd is in the arms. In order not to generate a lot here and why. - Oleksandr