1

I know I can write:

 $('.2020').css("padding", "20px");

But how do I write it like:

 $('.a').children('img').children('.2020').css("padding", "20px");

 <div class"a">
 <img class="2020" src="img/swatch/2020.jpg" >
 <img class="2021" src="img/swatch/2021.jpg" >
 <img class="2022" src="img/swatch/2022.jpg" >
 </div>

http://jsfiddle.net/ssRYk/

j08691
  • 204,283
  • 31
  • 260
  • 272
user2238083
  • 583
  • 2
  • 9
  • 21

2 Answers2

1

Your selector $('.a').children('img').children('.2020') tries to find elements with class 2020 which is inside an img element which is inside an element with class a.

Ex

<div class="a">
    <img src="img/swatch/2020.jpg" >
        <span class="2020"></span>
    </img>
</div>

But in your case the img element has the class attribute, so you have two choices either concatenate the img and .2020 selector like .children('img.2020') or find the img elements using .children('img') and filter elements with class within that set using .filter('.2020')

If you want to retain the same structure, then you can

$('.a').children('img').filter('.2021').css("padding", "5px");

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Your fiddle and code above both have an error, it is missing the = in your class="a"

You are saying look for all elements that have the class a. Than look for children that are images. Now look for images that have a child with the class 2021. Since images can not have children, that code would never return anything.

You can combine the two children statements with one selector instead of doing multiple actions.

$('.a').children('img.2021').css("padding", "5px");

You could also write it without the children in just one selector

$('.a > img.2021').css("padding", "5px");

The alternative is filtering.

epascarello
  • 204,599
  • 20
  • 195
  • 236