1

I have a paragraph or h1 with "the color of this item is Magenta" or "this output is Red". The text with color (red, black, cyan, magenta or yellow) could be somewhere on the paragraph or h1 tag.

My code so far.

HTML

<div id="foo">
  red magenta yellow black blue
</div>
<h1>magenta toner cartridge</h1>

CSS

.red{
  color: red;   
}
.magenta{
  color: magenta;   
}

JAVASCRIPT

$("div:contains('magenta')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("magenta", "<span class='magenta'>magenta</span>"));
});

$("div:contains('red')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("red", "<span class='red'>red</span>"));
});


$("h1:contains('magenta')").each(function () {
  $(this)
    .html($(this)
    .html()
    .replace("magenta", "<span class='magenta'>MAGENTA</span>"));
});

Question How can I change the background and text color of the word Magenta and Red dynamically based on the text within the element?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
Riyas Rawther
  • 67
  • 1
  • 4

1 Answers1

1

Something like this would work:

 




var colors={'red':{'background-color':'#ff0000',"color":'#ffffff'},
            'black':{'background-color':'#000000',"color":'#ffffff'},
            'cyan':{'background-color':'#00ffff',"color":'#ffffff'},
            'magenta':{'background-color':'#ff00ff',"color":'#ffffff'},
            'yellow':{'background-color':'#ffff00',"color":'#000000'}
            };
            


function colorize(colorsArr, selector) {
  $.each(colorsArr, function(color, obj) {
    var regex = new RegExp('(' + color + ')', 'gi');
    var style = ' style="' + JSON.stringify(obj).replace(/[{"}]/g, '').replace(',', ';') + '" '
    var $element = $(selector);
    var curComtent = $element.html();
    if (curComtent.match(regex)) {
      var newContent = curComtent.replace(regex, '<span ' + style + '>$1</span>');
    }
    $element.html(newContent); 
  });
}


colorize(colors, '.test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="test">
  I have a paragraph or h1 with "the color of this item is Magenta" or "this output is Red". So how can I change the background and text color of the word Magenta and Red dynamically. The text with color (red, black, cyan, magenta or yellow) could be somewhere
  on the paragraph or h1 tag.
</p>
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133