tags:

views:

2833

answers:

5

Hi, I need to find an element based on a specific css attribute. the css is applied inline and I can not use a class. Is there anyway to achieve this in jquery?

+5  A: 

You could use an attribute selector

For example

$(":radio [style*='regular']")

would return a wrapped set of any input radios that contain 'regular' in the style attribute

Russ Cam
+2  A: 

Something like:

$('selector').each(function() {
    if($(this).attr('style').indexOf('font-weight') > -1) {
        alert('got my attribute');
    }
});
karim79
.indexOf can return 0, which will be evaluated to false
mkoryak
@mkoryak - thanks, just realised, fixed it.
karim79
A: 
var ccsStyle="font-weight:bold";
var els = [];
$("*").each(function(){
  var st = $(this).attr("style");
  if(st.indexOf(cssStyle) > -1) els.push(this);
});
//do stuff with els
mkoryak
A: 

You could use the attribute flag and use contains if you know the specific format that it's in.

$("[style*='position']")

This would find all the elements that define the position css attribute.

MacAnthony
+1  A: 

I think you might be able to write a custom jquery selector to do this

for example if you want to do select by certain style attribute , you can do

 jQuery.extend(jQuery.expr[':'], {
    styleEquals: function(a, i, m){
     var styles = $(a).attr("style").split(" ")
     var found = false;
     for (var i = 0; i < styles.length; i++) {
      if (styles[i]===m[3]) {
       found = true;
       break;
      }
     }
     return found;
    }
});

Then it can be used in conjuction with any other selector you can select all input elements with certain style like this

$('input:styleEquals('width=10px')')
Surya
this functionality is already included in the jQuery language. all you need is $('selector[cssAttribute = value]')
ScottSEA
jquery inbuilt selector works only if its an exact match , so it will only match if style = "absolute;" not if style = "absolute; left" . So the solution I posted is for finding all elements with absolute value not only exact matches
Surya
@Surya: yep, I had a bad case of cerebro-rectal interitis. Don't know what I was thinking.
ScottSEA
I am getting (styles[i].equals(m[3])) is not a functionon this line if (styles[i].equals(m[3])) {
Sammy
@Sammy I updated the code ..I didnt test it intially ..i just typed it in the browser.
Surya
@Surya, Thanks Surya I have already made that change using === insteadnow if call it like var ele = $("span:styleEquals('overflow=auto')");alert(ele.Id);the alert is always undefined.
Sammy