MSG
MSG

Reputation: 41

How to replace plain text with a specific value with the same text but <font> tags around it with JS or jQuery on page load

I have the following button:

<button class="sz-grid-dropdown sz-grid-button" data-qa="sz-dropdown">SIZE 10</button>

I need to replace it on page load with:

<button class="sz-grid-dropdown sz-grid-button" data-qa="sz-dropdown"><font color="red">SIZE 10</font></button>

The other sizes look the same, the only thing that's different is the text between the button tags: US 9, US 10, etc.

I essentially need to replace "SIZE 10" with "<font color="red">SIZE 10</font>" for Macro automation purposes on an existing website. I'm going to have different sizes be different colors.

I wish I could style it with a styling extension but all the button tags have nothing relating to the size.

A javascript snippet or jQuery snippet would be appreciated, I'll then have to find how to make it load onto the site on page load so it changes the text color. But that part is easier.

Upvotes: 0

Views: 64

Answers (2)

BritishSam
BritishSam

Reputation: 1090

How about something like below?

var colors = ["red", "blue", "green"]
var i = 0;

$('button').each(function(){
  if($(this).is(':contains("SIZE ")')){
      $(this).css('color', colors[i]);
      i++
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="sz-grid-dropdown sz-grid-button" data-qa="sz-dropdown">
  SIZE 10
 </button>
 <button class="sz-grid-dropdown sz-grid-button" data-qa="sz-dropdown">
  SIZE 9
 </button>
 <button class="sz-grid-dropdown sz-grid-button" data-qa="sz-dropdown">
  SIZE 8
 </button>

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35096

The easiest would be to add a css style. Something like

button.sz-grid-dropdown.sz-grid-button {
  color: red;
}

If the buttons you want to style aren't selectable by class like this, you can use jQuery:

var buttons = $("button").filter(function() {
  return (this.innerText === "SIZE 10");
});

Rather than adding the font tag, you could just add a class to these buttons, and set the css to style with color:red

In HTML5 you should avoid using FONT (and B, I, U) tags. You can use SPAN instead and classes to style your elements

Upvotes: 1

Related Questions