0

please help to solve the problem

on the page, there are several img. some have the attribute

style="line-height: 1.538em; float: right;"

, some have attribute

style="line-height: 1.538em; float: left;"

I would like to js or jquery to select only those img, whose float: right;

  • 3
    I don't think such selector exists, can't you simply use different class for each image then it is as trivial as `$(".img_left")`? – Shadow The GPT Wizard Aug 04 '13 at 10:24
  • You dont really want to do that, would be a very slow selector. I suggest you find a way to give them a class and select them with the class – Martijn Aug 04 '13 at 10:26
  • 2
    I'm going to write this here: Allot of people do this: `if( $(this).css('float') === "left" )`. A better solution would be `if(this.style.cssFloat =='left')`. This is better for performance and allot faster than making jQuery select each item and loop through them – Martijn Aug 04 '13 at 10:31
  • @ShadowWizard: [There is](http://stackoverflow.com/a/18041926/157247), provided the text `float: right` is actually in the `style` attribute. – T.J. Crowder Aug 04 '13 at 10:32
  • @T.J.Crowder well, it looks pretty.. hackish to me. Nothing wrong with that, but still. :) – Shadow The GPT Wizard Aug 04 '13 at 11:11
  • @ShadowWizard: No more hackish than selecting on any other substring. I do think it would be better to identify these elements in a different way. :-) – T.J. Crowder Aug 04 '13 at 11:17

4 Answers4

2

In this mode you loop each image inside your dom and search only elements image with css: float:left Try this:

$('img').each(function(index){
   if(this.style.cssFloat =='left'){
     //your code here
   }
});
Martijn
  • 15,791
  • 4
  • 36
  • 68
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
1

A bit tricky, but i would try something like:

$('img').each(function() {
  if ($(this).css('float') === "left") {
    //my stuff
  }
});

Then again, giving a custom class to what you want to select is probably a better idea.

Florian
  • 3,366
  • 1
  • 29
  • 35
1

You could use an "attribute contains" selector (*=):

var imgs = $('img[style*="float: right"], img[style*="float:right"]');

(Note I've allowed for there being a single space, or not.) But it seems quite delicate and may be slow (doesn't really matter if you do it once, might matter if you do it a lot). Instead, I'd probably add a class to the relevant images. This will be faster on modern browsers than the each loops other answers suggest, however, as the work can be done within the browser's selector engine rather than in the JavaScript layer.

Also note that that will only match if the actual img tag has float: right within its style attribute.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

try $('img[style*="float:left"]')

Elpy
  • 272
  • 1
  • 4