-2

Quick question: Our CMS uses CKEditor to allow our clients to edit their site. The front-end styles uses a pre tag. So we've styled out the pre tag exactly how we want it to look. However, their staff has copy and pasted from another site and it has changed the styling due to inline styles. So I set-up this script to remove all inline styles:

$("pre").attr({style : ""});

However, I am having an issue with some of the pre tags need to have the text-align:center; inline tag. How can I set-up the script to allow the pre tag to only have text-align?

Cody
  • 25
  • 7
  • 1
  • Check if you have an inline property named `text-align`. To check that, [here](https://stackoverflow.com/a/11306872/3168859) is a nice answer. And then, if the style exists, add it again after doing `$("pre").attr({style : ""});`.. Isn't that what you are trying to achieve? – Lal Jun 13 '17 at 16:05
  • 1
    "*I am having an issue with some of the `
    ` tags need to have the `text-align:center` [property]*" – which specific `
    ` tags? How should we clarify which of those tags should, and shouldn't, have `text-align: center`? Where's your – [mcve] – html that reproduces your problem?
    – David Thomas Jun 13 '17 at 16:13

2 Answers2

2

Just loop through the tag and check for them

$("pre").each(function(){
    var center = (this.style['text-align'] == 'center');
    $(this).attr({style : ""});
    if (center){
        $(this).css({'text-align': 'center'});
    }
});
Musa
  • 96,336
  • 17
  • 118
  • 137
1

While Musa's answer is perfectly acceptable, this answer is slightly more jQuery-centric:

$('pre').each(function () {
  var $this = $(this);
  var textAlign = $this.css('text-align') == 'center' ? 'center' : '';

  $this
    .removeAttr('style')
    .css('text-align', textAlign);
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153