开发者

How can I remove programmatically-added styles in Chrome?

开发者 https://www.devze.com 2023-03-13 17:38 出处:网络
I have a simple paragraph with two buttons which respectively color it and remove the color. The color removal works in Firefox, but not in Chrome (chromium-browser, to be precise). If I were to add t

I have a simple paragraph with two buttons which respectively color it and remove the color. The color removal works in Firefox, but not in Chrome (chromium-browser, to be precise). If I were to add the style through a style attribute ( <p id="paragraph" style="color: #f00;"> ) rather than programmatically ( $('#paragraph').css('color', '#f00'); or d开发者_StackOverflow社区ocument.getElementById('paragraph').style.color="#f00"; ), then the color removal would work on both browsers. Unfortunately, this is impossible in my real-world situation. How else can I make this work?

The code looks like this:

html

<p id="paragraph">TARGET</p>
<input type="button" value="Style me" onclick="styleIt();" />
<input type="button" value="Strip styles" onclick="stripStyles();" />

javascript

function styleIt()
{
    $('#paragraph').css('color', '#f00');
}

function stripStyles()
{
    $('#paragraph').removeAttr("style");
}

jsFiddle: http://jsfiddle.net/qBtYW/10/

P.S. I'm pretty sure the problem resides in the way removeAttr behaves in different browsers, but I could be wrong.

edit I realise I could use css('color', '') but I'm looking for something that will remove all styles, even those I didn't know were there...


You could just set the style attribute equal to an empty string:

function stripStyles()
{
  $('#paragraph').attr('style', "");
}

I'm not sure why removeAttr is having problems, but I think this should work in all browsers.

0

精彩评论

暂无评论...
验证码 换一张
取 消