Search code examples
javascriptjquerychildren

target img class name


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/


Solution

  • 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.