views:

27

answers:

2

Hi, I need to style images of a JPG format only. (jQuery)

I need class to be applied to jpeg's when it's placed in specific container (not all jpg's on the page).
For example:

<img src="non-jpeg.jpg"> <!--no changes made-->
<img src="jpeg-image.jpg"> <!--no changes made-->
<div class="spec-container"><img src="jpeg-image.jpg"></div> <!--changes applied-->

to be like this

<img src="non-jpeg.jpg">
<img src="jpeg-image.jpg">
<div class="spec-container"><img src="jpeg-image.jpg" class="styled"></div>  

Thanks in advance!

+2  A: 

You can do it using an attribute-ends-with selector for images inside that container, like this:

$(".spec-container img[src$='.jpg']").addClass("styled");

If you want the selector a bit more forgiving, use .filter() like this:

$(".spec-container img").filter(function() {
  return /\.[jpg$|jpeg$]/i.test(this.src);
}).addClass("styled");
Nick Craver
+1 but maybe add `.jpeg` in the mix for completeness' sake. Also, is this case insensitive?
Pekka
Oh and congratulations to breaking the 100k barrier!
Pekka
Worked great. Thanks.
dessol
In addition - how can I list there a couple of formats?
dessol
@Pekka - updated to handle the various cases and thanks :) @dessol - you can modify the regex I have above for any additional formats.
Nick Craver
A: 

You can just do that with pure CSS. Put the class="styled" on all your images, then in the CSS:

img.styled
{
    /* put styles that apply to non-styled images here */
}

div.spec-container img.styled
{
    /* put styles here that you want only applied to the "styled" images */
}
GendoIkari
thanks. I know. But I need jquery in my case
dessol
... and I need curtain jpg format to be styled only. CSS doesn't provide me with that option
dessol