简体   繁体   中英

Using JQuery, how do I target an element with a style attribute in IE?

With JQuery, I am targeting the following:

<li style="margin-left: 15px;">blah<li>

with this code:

$(".block-category-navigation li[style='margin-left: 15px;']").addClass('sub-menu'); 

It works great in firefox, but doesn't work at all in IE. Does IE ignore the style selector? Anyway around if so

After checking this in IE8's console, I found that it's turning 'margin-left' into 'MARGIN-LEFT'.

In IE this selector will work:

$(".block-category-navigation li[style='MARGIN-LEFT: 15px']").addClass('sub-menu'); 

You could either have both upper & lower case selectors, or use a loop to check the style attribute like so:

$('.block-category-navigation li[style]').each(function() {
    $this = $(this);
    if ($this.attr('style').match(/margin-left: 15px/i)) {
        $this.addClass('sub-menu');
    }
});

UPDATE

Since I don't want to give you code that doesn't work, I've setup this working example here: http://jsfiddle.net/YB7uV/6/

You can use the marginLeft css attribute with the each() method...not sure if there's a better way though

$(".block-category-navigation li[style]").each(function(){
 if($(this).css("marginLeft") == '15px')
    $(this).addClass("myclass");

});

We need to see the code including the ul tag as well as the stylesheets that use all of the styles. It is likely in the way you handle your CSS, not with jQuery. I will say that your hyphen use is cause for concern, though as I said before, without the full picture it's difficult to diagnose. Since you're adding a class with a hyphen in the name, jQuery is could be referencing that class as a property rather than a string. Firefox is a bit more graceful in handling Javascript so IE might simply ignore the class addition if the naming is off. You could also try changing that class from sub-menu to submenu and just see if IE plays along better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM