简体   繁体   中英

Jquery change text and css for part of text

To simplify, I have a label set in my html as:

 <label id ="lblApptDateTime" >Appointment</label>

On an event I am changing the lext of lblApptDateTime to Appointment with an asterisk. I want the asterisk to be red color and in bold font. How do i achieve that ?

Here's what I am changing the text on the event:

  $("#lblApptDateTime").html("Appointment" + "*");

Need to change the color of asterisk to red and in bold font.

You can add the asterisk in an :after pseudo-element. This way you can style it to your liking, apart from the text.

.asterisk:after {
    content: '*';
    color: red;
}

In your JavaScript, instead of adding the asterisk inside the label, you just add the class asterisk to it:

$("#lblApptDateTime").html("Appointment").addClass("asterisk");

You can also use toggleClass() instead of addClass() if the asterisk should be toggle-able.

Here's a working fiddle . Since I didn't have any other event available, I used hover .

Wrap it in a span and use a class

 $("#lblApptDateTime").html('Appointment' + '<span class="red">*</span>'); 
 .red { color: red; font-weight: bold } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <label id="lblApptDateTime">Appointment</label> 

You'll need to put it in a new styled element like a span , which you can do with append :

$("#lblApptDateTime").append($("<span>").css("color", "red").text("*"));

Or addClass() instead of using css() and style it appropriately.

HTML:

$("#lblApptDateTime").html("Appointment" + "<span class="red">*</span>");

CSS:

span.red {
  color: red;
  font-weight: bold;
}

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