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?
+2
A:
Something like:
$('selector').each(function() {
if($(this).attr('style').indexOf('font-weight') > -1) {
alert('got my attribute');
}
});
karim79
2009-07-24 20:48:21
.indexOf can return 0, which will be evaluated to false
mkoryak
2009-07-24 20:51:04
@mkoryak - thanks, just realised, fixed it.
karim79
2009-07-24 20:52:05
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
2009-07-24 20:49:58
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
2009-07-24 20:50:09
+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
2009-07-24 20:55:40
this functionality is already included in the jQuery language. all you need is $('selector[cssAttribute = value]')
ScottSEA
2009-07-24 21:00:15
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
2009-07-24 21:03:34
@Surya: yep, I had a bad case of cerebro-rectal interitis. Don't know what I was thinking.
ScottSEA
2009-07-24 21:05:41
I am getting (styles[i].equals(m[3])) is not a functionon this line if (styles[i].equals(m[3])) {
Sammy
2009-07-24 21:17:36
@Sammy I updated the code ..I didnt test it intially ..i just typed it in the browser.
Surya
2009-07-24 22:16:55
@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
2009-07-24 22:32:17